开发者

How do I print a List of anything in Scala?

开发者 https://www.devze.com 2023-03-19 16:16 出处:网络
At the moment I have a method that prints Ints def printList(args:开发者_C百科 List[Int]): Unit = {

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 Lists:

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:

 (
 )
 (
 )
0

精彩评论

暂无评论...
验证码 换一张
取 消