Ravi Reddy
Ravi Reddy

Reputation: 23

How to print array values in Scala? I am getting different values

Code:

object Permutations extends App 
{          
    val ar=Array(1,2,3).combinations(2).foreach(println(_))
}

Output:

[I@378fd1ac

[I@49097b5d
[I@6e2c634b

I am trying to execute this but I am getting some other values.

How to print array values in Scala? Can any one help to print?

Upvotes: 1

Views: 2787

Answers (2)

Manoj Kumar Dhakad
Manoj Kumar Dhakad

Reputation: 1892

You can't print array directly, If you will try to print it will print the reference of that array.

You are almost there, Just iterate over array of array and then on individual array and display the elements like below

Array(1,2,3).combinations(2).foreach(_.foreach(println))

Or Just convert each array to string and display like below

Array(1,2,3).combinations(2).foreach(x=>println(x.mkString(" ")))

I hope this will help you

Upvotes: 1

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Use mkString

object Permutations extends App {
   Array(1,2,3).combinations(2).foreach(x => println(x.mkString(", ")))
}

Scala REPL

scala> Array(1,2,3).combinations(2).foreach(x => println(x.mkString(", ")))
1, 2
1, 3
2, 3

When array instance is directly used for inside println. The toString method of array gets called and results in output like [I@49097b5d. So, use mkString for converting array instance to string.

Scala REPL

scala> println(Array(1, 2))
[I@2aadeb31

scala> Array(1, 2).mkString
res12: String = 12

scala> Array(1, 2).mkString(" ")
res13: String = 1 2

scala>

Upvotes: 1

Related Questions