Skip to content

Commit a9310f6

Browse files
committed
Make Show.fromToString null safe
Fixes #4689
1 parent db17f47 commit a9310f6

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

core/src/main/scala/cats/Show.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ object Show extends ScalaVersionSpecificShowInstances with ShowInstances {
6868
/**
6969
* creates an instance of [[Show]] using object toString
7070
*/
71-
def fromToString[A]: Show[A] = _.toString
71+
def fromToString[A]: Show[A] = String.valueOf(_)
7272

7373
final case class Shown(override val toString: String) extends AnyVal
7474
object Shown {

tests/shared/src/test/scala/cats/tests/ShowSuite.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,17 @@ class ShowSuite extends CatsSuite {
113113
val mapSorted: SortedMap[Int, String] = SortedMap(3 -> "three", 1 -> "one", 4 -> "four", 2 -> "two")
114114
assertEquals(show"$mapSorted", "SortedMap(1 -> one, 2 -> two, 3 -> three, 4 -> four)")
115115
}
116+
117+
test("fromToString should be consistent with toString on non-null references") {
118+
case class ExplicitToString() { override val toString = "explicit toString" }
119+
val show = Show.fromToString[ExplicitToString]
120+
assertEquals(show.show(ExplicitToString()), "explicit toString")
121+
}
122+
123+
test("fromToString should be null safe") {
124+
val show = Show.fromToString[AnyRef]
125+
assertEquals(show.show(null), "null")
126+
}
116127
}
117128

118129
final class ShowSuite2 extends munit.FunSuite {

0 commit comments

Comments
 (0)