加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:27:14 所属栏目:安全 来源:网络整理
导读:假设我有一些像这样的 Scala代码: // Outputs 1,4,9,16,25,36,49,64,81,100println( squares)def squares = { val s = for ( count - 1 to 10 ) yield { count * count } s.mkString(",");} 为什么我必须使用临时val?我试过这个: def squares = for ( cou
假设我有一些像这样的 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(",")

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

解决方法

有一个缺少的括号.您想在for-expression的结果上调用mkString方法.没有额外的括号,编译器认为你想在{count * cout}上调用mkString-method,这是一个Int.

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

scala> squares
res2: String = 1,100

无论如何,我建议你应该使用map方法:

scala> 1 to 10 map { x => x*x } mkString(",")
res0: String = 1,100

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读