我想执行一个函数三次。该函数碰巧返回一个字符串。
def doThingReturnString(): String = {
println("Did a thing, returned a string.")
"abcdef"
}
(1 to 3).foreach { n =>
doThingReturnString()
}
(1 to 3).foreach {
doThingReturnString()
}
Run Code Online (Sandbox Code Playgroud)
我希望两个循环都可以打印三行。而是,第一个循环打印三行,第二个循环打印一行。
做了一件事情,返回了一个字符串。
做了一件事情,返回了一个字符串。
做了一件事情,返回了一个字符串。
做了一件事情,返回了一个字符串。
为什么命名参数会使循环仅执行一次?
HTN*_*TNW 12
foreach需要一个功能Int => U(在哪里U可以是“任何”)。期。如果要忽略该参数,请使用下划线。
(1 to 3).foreach { _ => doThingReturnString() }
Run Code Online (Sandbox Code Playgroud)
当你写
(1 to 3).foreach { doThingReturnString() }
Run Code Online (Sandbox Code Playgroud)
花括号像括号一样
(1 to 3).foreach(doThingReturnString())
Run Code Online (Sandbox Code Playgroud)
的参数foreach必须为Int => U,但在这里为String。String可以将A 隐式转换为Int => U,因为String可以将 A 隐式转换为WrappedString,将其视为集合类型,特别是将Seq[Char]其视为a ,可以将其向上转换为PartialFunction[Int, Char]从索引到元素,可以将其向上转换为Int => Char。因此,您基本上已经写了
val temp = doThingReturnString()
(1 to 3).foreach { i => temp.charAt(i) }
Run Code Online (Sandbox Code Playgroud)
出现这种情况的原因是,将Seq[A]s视为PartialFunction[Int, A]s非常明智。能够像对待其他集合类型一样对待字符串也是明智的做法,因此我们进行了隐式转换,以String使用Scala的集合体系结构扩充Java 。将它们放在一起,使Strings变成Int => Chars,会产生令人惊讶的行为。