At the moment I have a method that prints Ints
def printList(args:开发者_C百科 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)
}
You just need to make the method generic
def printList[A](args: List[A]): Unit = {
args.foreach(println)
}
def printList[T](args: List[T]) = args.foreach(println)
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:
(
)
(
)
精彩评论