Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala foreach循环在打印列表元素N次时出现意外编译错误_Scala_Functional Programming - Fatal编程技术网

Scala foreach循环在打印列表元素N次时出现意外编译错误

Scala foreach循环在打印列表元素N次时出现意外编译错误,scala,functional-programming,Scala,Functional Programming,我刚开始学习Scala,我正在尝试解决一个关于HackerRank的非常简单的练习 我得到一个数字和一个列表作为输入,我想把它们打印N次 这是我写的函数: def f(num:Int,arr:List[Int]):List[Int] = { arr.foreach((element:Int) => print((s"$element" + "\n") * num)) } 错误: Solution.scala:3: error: type mismatch; found :

我刚开始学习Scala,我正在尝试解决一个关于HackerRank的非常简单的练习

我得到一个数字和一个列表作为输入,我想把它们打印N次

这是我写的函数:

def f(num:Int,arr:List[Int]):List[Int] = {
    arr.foreach((element:Int) => print((s"$element" + "\n") * num))
}
错误:

Solution.scala:3: error: type mismatch;
 found   : Unit
 required: List[Int]
    arr.foreach((element:Int) => println((s"$element" + "\n") * num))
               ^
one error found

如果我在scala(v2.13)控制台中运行相同的东西,我会得到预期的输出

输出(发送到StdOut)与从方法或函数返回的结果不同
f()
被定义为返回
List[Int]
foreach()
返回
Unit
,因此代码不一致。如果您只需要所需的标准输出,那么重新定义
f()
以返回
Unit
@jwvh您能帮我解决吗?我再次尝试返回
arr
,但仍然无法接受。这里有一个到@pissall的链接,这是一个跨语言的普遍现象。函数应该返回适当的值。如果您对此有疑问,那么我建议您阅读有关Scala的书籍,例如。@pissall;HackerRank的挑战与StdOut无关。因此,不要使用
print()
println()
(或
foreach()
)。您应该创建一个新的
列表[Int]
,包含所需的内容,并从方法
f()
返回该内容。OP的问题是,您是要打印新列表,还是要返回新列表?你应该先弄清楚你想做什么,然后试着找到解决办法。