2

Why unable to access the String value ?

I would expect the s1 to be "a" but instead its Ljava.lang.String;@d70d7a ?

 val it = Iterator("(a,((a,b),1.0))")             //> it  : Iterator[String] = non-empty iterator

 val s1 = it.next.replace("(" , "").replace(")" , "").split(",").toString.split(",")
                                                  //> s1  : Array[String] = Array([Ljava.lang.String;@d70d7a)
 println("s1 is "+s1(0))                          //> s1 is [Ljava.lang.String;@d70d7a
Machavity
  • 30,841
  • 27
  • 92
  • 100
blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • 4
    You probably want `mkString(",")` instead of `toString`. `toString` on an array will produce the ugly `[Ljava.lang.String;@d70d7a`. – gourlaysama Jul 25 '14 at 13:25

2 Answers2

3

Let's go command-by-command:

val it = Iterator("(a,((a,b),1.0))")
// here we got iterator on one String

val s1 = it.next // "(a,((a,b),1.0))"
        .replace("(" , "") // "a,a,b),1.0))"
        .replace(")" , "") // "a,a,b,1.0"
        .split(",") // multiple lines in array: "a", "a","b","1.0"
        .toString // Array[String].toString returns what you got: Ljava.lang.String;@d70d7a
        .split(",") // one String (because there's no "," signs)

Maybe you should run toList before toString, because toString is defined in a way you expect it to be defined in this implementation of List:

val s1 = ...
        .split(",")
        .toList
        .toString
        ...

Maybe you should look at Java: split() returns [Ljava.lang.String;@186d4c1], why? for clarification.

Community
  • 1
  • 1
Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48
2

.split(",") makes Array and .toString doesn't work on Array and after that you are again spliting by .split(",") which i don't think helpful.

and you can also use replaceAll in place of multiple replace

scala>  val it = Iterator("(a,((a,b),1.0))")         
it: Iterator[String] = non-empty iterator

scala>  val s1 = it.next.replaceAll("[()]" , "").split(",")
s1: Array[String] = Array(a, a, b, 1.0)

scala> println("s1 is "+s1(0))    
s1 is a
Govind Singh
  • 15,282
  • 14
  • 72
  • 106