假设我有一些像这样的Scala代码:
// Outputs 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
println( squares)
def squares = {
val s = for ( count <- 1 to 10 )
yield { count * count }
s.mkString(", ");
}
Run Code Online (Sandbox Code Playgroud)
为什么我必须使用临时val?我试过这个:
def squares = for ( count <- 1 to 10 )
yield { count * count }.mkString(", ")
Run Code Online (Sandbox Code Playgroud)
无法使用此错误消息进行编译:
error: value mkString is not a member of Int
def squares = for ( count <- 1 to 10 ) yield { count * count }.mkString(", ")
Run Code Online (Sandbox Code Playgroud)
不mkString应该在for循环返回的集合上调用?
mic*_*ebe 18
有一个缺少的括号.您想要mkString在for-expression 的结果上调用该方法.没有额外的括号,编译器认为你想调用mkString-method {count * cout}就是一个Int.
scala> def squares = (for ( count <- 1 to 10 ) yield { count * count }).mkString(", ")
squares: String
scala> squares
res2: String = 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
Run Code Online (Sandbox Code Playgroud)
无论如何,我建议你应该使用这个map方法:
scala> 1 to 10 map { x => x*x } mkString(", ")
res0: String = 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
Run Code Online (Sandbox Code Playgroud)
只需在for循环周围加上括号即可:
scala> (for (count <- 1 to 10) yield { count * count }).mkString(", ")
Run Code Online (Sandbox Code Playgroud)
res0: String = 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
| 归档时间: |
|
| 查看次数: |
945 次 |
| 最近记录: |