NikRED
NikRED

Reputation: 1195

Why printing List[Array[String]] does not output values?

I am trying to understand the output which i got from below code, It shows some alpha numeric values prefix with @. how can i change it to ("Hello,world"),("How,are,you")

Scala Code:

val words = List("Hello_world","How_are_you" )
val ww= words.map(line=>line.split("_"))
println(ww)

output

List([Ljava.lang.String;@7d4991ad, [Ljava.lang.String;@28d93b30)

Upvotes: 0

Views: 129

Answers (4)

jq170727
jq170727

Reputation: 14655

Perhaps mkString is what you are looking for?

scala> val ww2 = words.map(line=>line.split("_").mkString(","))
ww2: List[String] = List(Hello,world, How,are,you)

scala> println(ww2)
List(Hello,world, How,are,you)

Upvotes: 1

Mario Galic
Mario Galic

Reputation: 48410

To prettify Array printing consider ScalaRunTime.stringOf like so

import scala.runtime.ScalaRunTime.stringOf
println(stringOf(ww))

which outputs

List(Array(Hello, world), Array(How, are, you))

As explained by @Dmytro, Arrays are bit different from other Scala collections such as List, and one difference is they are printed as hashCode representations

public String toString() {
  return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

instead of value representations.

Upvotes: 4

Dmytro Mitin
Dmytro Mitin

Reputation: 51658

Add .toList

val ww = words.map(line=>line.split("_").toList)
// List(List(Hello, world), List(How, are, you))
ww == List(List("Hello", "world"), List("How", "are", "you")) // true

Otherwise ww is a List[Array[String]] rather than List[List[String]] and println shows hashcodes of arrays.

Or maybe you're looking for

val ww1 = words.map(_.replace("_", ","))
// List(Hello,world, How,are,you)
ww1 == List("Hello,world", "How,are,you") // true

Upvotes: 6

naval jain
naval jain

Reputation: 393

The output here is as expected. It just printed out the list with fully qualified name for the corresponding string with @ hashcode. Standard in most of the JVM languages.

Upvotes: 2

Related Questions