0

Consider the following in REPL

scala> val  a = "1 2 3"
a: String = 1 2 3

scala> a.split(" ")
res0: Array[String] = Array(1, 2, 3)

Consider the following in compiler

  val s = readLine()
  println(s.split(" ")) // outputs [Ljava.lang.String;@5ebec15
  println(s.toList)     // outputs List(1,  , 2,  , 3)

Why is there different output for the same function, namely

Array(1, 2, 3)

vs

[Ljava.lang.String;@5ebec15

I would assume both have the same output

Am I missing something

Kevin
  • 2,187
  • 4
  • 26
  • 35
  • You're missing http://stackoverflow.com/q/3328085/1296806 or http://stackoverflow.com/q/17634427/1296806 – som-snytt Mar 22 '16 at 07:43

3 Answers3

3

The repl output is not the same as the println output. The println outputs the .toString:

scala>  val  a = "1 2 3"
a: String = 1 2 3

scala> a.split(" ").toString
res0: String = [Ljava.lang.String;@5f84486a

In some cases the repl will print out the .toString, eg. when the object is a List or a case object. But when it comes to an Array, it will be smarter and actually print the array's contents.

pedrofurla
  • 12,763
  • 1
  • 38
  • 49
0

I tried the following in a worksheet and i see no difference.

val s = "1 2 3"                                 //> s  : String = 1 2 3
s.split(" ")                                    //> res0: Array[String] =     Array(1, 2, 3)
  println(s.toList)                               //> List(1,  , 2,  , 3)

The return from s.split is an array in both cases. It is when you pass the array to the println function that it outputs a string which is actually correct.

Som Bhattacharyya
  • 3,972
  • 35
  • 54
0

Regarding your follow up question, not exactly the same output as the REPL, but the following two ways will print the elements of the array. Also see discussions in Printing array in Scala

scala> val  a = "1 2 3"
a: String = 1 2 3

scala> println(a.split(" ")) // outputs a.split(" ").toString
[Ljava.lang.String;@5fd62371

scala> println(runtime.ScalaRunTime.stringOf(a.split(" ")))
Array(1, 2, 3)

scala> println(a.split(" ").deep)
Array(1, 2, 3)
Community
  • 1
  • 1
sxiang3
  • 1
  • 1