deltanovember
deltanovember

Reputation: 44041

How do I print a List of anything in 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?

Upvotes: 28

Views: 59623

Answers (5)

Jan Clemens Stoffregen
Jan Clemens Stoffregen

Reputation: 887

Or a recursive version to practise :)

1 - Declare your List

val myCharList: List[Char] = List('(',')','(',')')

2 - Define your method

def printList( chars: List[Char] ): Boolean = {
  if ( chars.isEmpty ) true //every item of the list has been printed
  else {
    println( chars.head )
    printList( chars.tail )
  }
}

3 - Call the method

printList( myCharList )

Output:

 (
 )
 (
 )

Upvotes: 1

Kevin Wright
Kevin Wright

Reputation: 49685

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

Upvotes: 56

IttayD
IttayD

Reputation: 29113

def printList[T](args: List[T]) = args.foreach(println)

Upvotes: 3

Thomas Lockney
Thomas Lockney

Reputation: 2587

You just need to make the method generic

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

Upvotes: 8

Alexey Romanov
Alexey Romanov

Reputation: 170713

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)
}

Upvotes: 27

Related Questions