为什么我不能在for-yield表达式上调用方法?

198*_*ual 4 scala

假设我有一些像这样的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

有一个缺少的括号.您想要mkStringfor-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)

  • 他的理解只是你提供的完全相同的地图方法的语法糖.在我看来,你想要使用的只是品味问题. (2认同)

Arj*_*ijl 5

只需在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