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

时间:2010-06-02 06:08:58

标签: 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(", ");
}

为什么我必须使用临时val?我试过这个:

def squares = for ( count <- 1 to 10 )
                  yield { count * count }.mkString(", ")

无法使用此错误消息进行编译:

error: value mkString is not a member of Int
   def squares = for ( count <- 1 to 10 ) yield { count * count }.mkString(", ")

不应该在mkString循环返回的集合上调用for吗?

3 个答案:

答案 0 :(得分:18)

缺少括号。您想在mkString - 表达式的结果上调用for方法。如果没有额外的括号,编译器会认为您想在mkString {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

无论如何,我建议您使用map方法代替:

scala> 1 to 10 map { x => x*x } mkString(", ")
res0: String = 1, 4, 9, 16, 25, 36, 49, 64, 81, 100

答案 1 :(得分:5)

只需将括号括在for循环中即可:

scala> (for (count <- 1 to 10) yield { count * count }).mkString(", ") 

res0: String = 1, 4, 9, 16, 25, 36, 49, 64, 81, 100

答案 2 :(得分:3)

当您在第二个示例中调用mkString时,它不会在集合上调用,而是在返回的每个单独的整数上调用,因此出现错误消息:mkString is not a member of Int
如果您想在for..yield表达式本身上调用方法,则需要将其括起来:

def squares = (for (count <- 1 to 10) yield { count * count }).mkString(", ")
相关问题