如何在 Scala 中打印任何内容的列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6639377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:11:12  来源:igfitidea点击:

How do I print a List of anything in Scala?

scala

提问by deltanovember

At the moment I have a method that prints Ints

目前我有一个打印 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?

我如何修改它以便它足够灵活以打印任何内容的列表?

回答by Kevin Wright

You don't need a dedicated method, the required functionality is already right there in the collection classes:

您不需要专用方法,所需的功能已经在集合类中:

println(myList mkString "\n")

mkStringhas two forms, so for a List("a", "b", "c"):

mkString有两种形式,所以对于 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 \nas the separator and passed the resulting string to println

我的例子只是用作\n分隔符并将结果字符串传递给println

回答by Alexey Romanov

Since printlnworks on anything:

由于println适用于任何事情:

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

Or even better, so you aren't limited to Lists:

甚至更好,因此您不仅限于Lists:

def printList(args: TraversableOnce[_]): Unit = {
  args.foreach(println)
}

回答by Thomas Lockney

You just need to make the method generic

你只需要使方法通用

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

回答by IttayD

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

回答by Jan Clemens Stoffregen

Or a recursive version to practise :)

或者一个递归版本来练习:)

1 - Declare your List

1 - 声明你的清单

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

2 - Define your method

2 - 定义你的方法

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

3 - 调用方法

printList( myCharList )

Output:

输出:

 (
 )
 (
 )