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?
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
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With