Reputation: 44041
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
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
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
Reputation: 2587
You just need to make the method generic
def printList[A](args: List[A]): Unit = {
args.foreach(println)
}
Upvotes: 8
Reputation: 170713
Since println
works on anything:
def printList(args: List[_]): Unit = {
args.foreach(println)
}
Or even better, so you aren't limited to List
s:
def printList(args: TraversableOnce[_]): Unit = {
args.foreach(println)
}
Upvotes: 27