Skip to content

Commit 8b65ff4

Browse files
authored
Merge pull request scala#6706 from som-snytt/issue/stringof-npe
Avoid NPE in replStringOf
2 parents 14da628 + 66a062a commit 8b65ff4

File tree

2 files changed

+16
-10
lines changed

2 files changed

+16
-10
lines changed

src/library/scala/runtime/ScalaRunTime.scala

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -254,12 +254,12 @@ object ScalaRunTime {
254254
}
255255

256256
/** stringOf formatted for use in a repl result. */
257-
def replStringOf(arg: Any, maxElements: Int): String = {
258-
val s = stringOf(arg, maxElements)
259-
val nl = if (s contains "\n") "\n" else ""
260-
261-
nl + s + "\n"
262-
}
257+
def replStringOf(arg: Any, maxElements: Int): String =
258+
stringOf(arg, maxElements) match {
259+
case null => "null toString"
260+
case s if s.indexOf('\n') >= 0 => "\n" + s + "\n"
261+
case s => s + "\n"
262+
}
263263

264264
// Convert arrays to immutable.ArraySeq for use with Java varargs:
265265
def genericWrapArray[T](xs: Array[T]): ArraySeq[T] =

test/junit/scala/runtime/ScalaRunTimeTest.scala

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import org.junit.runners.JUnit4
1010
class ScalaRunTimeTest {
1111
@Test
1212
def testStringOf(): Unit = {
13-
import ScalaRunTime.stringOf
13+
import ScalaRunTime.{replStringOf, stringOf}
1414
import scala.collection._
1515

1616
assertEquals("null", stringOf(null))
@@ -51,9 +51,15 @@ class ScalaRunTimeTest {
5151
assertEquals("(Array(0),1,2)", stringOf((Array(0), 1, 2)))
5252

5353
val x = new Object {
54-
override def toString(): String = "this is the stringOf string"
54+
override def toString(): String = "this is the stringOf string"
5555
}
56-
assertEquals(stringOf(x), "this is the stringOf string")
57-
assertEquals(stringOf(x, 2), "this is the stringOf string")
56+
assertEquals("this is the stringOf string", stringOf(x))
57+
assertEquals("this is the stringOf string", stringOf(x, 2))
58+
59+
val tpolecat = new Object {
60+
override def toString(): String = null
61+
}
62+
assertEquals(null, stringOf(tpolecat))
63+
assertEquals("null toString", replStringOf(tpolecat, 100))
5864
}
5965
}

0 commit comments

Comments
 (0)