Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print a List of anything in Scala?

Tags:

scala

At the moment I have a method that prints Ints

def printList(args: List[Int]): Unit = {
  args.foreach(println)
}

How do I modify this so it is flexible enough to print a list of anything?

like image 729
deltanovember Avatar asked Sep 06 '25 03:09

deltanovember


2 Answers

You don't need a dedicated method, the required functionality is already right there in the collection classes:

println(myList mkString "\n")

mkString has two forms, so for a List("a", "b", "c"):

myList.mkString("[",",","]") //returns "[a,b,c]"
myList.mkString(" - ") // returns "a - b - c"
//or the same, using infix notation
myList mkString ","

My example just used \n as the separator and passed the resulting string to println

like image 85
Kevin Wright Avatar answered Sep 09 '25 13:09

Kevin Wright


Since println works on anything:

def printList(args: List[_]): Unit = {
  args.foreach(println)
}

Or even better, so you aren't limited to Lists:

def printList(args: TraversableOnce[_]): Unit = {
  args.foreach(println)
}
like image 28
Alexey Romanov Avatar answered Sep 09 '25 12:09

Alexey Romanov