【问题标题】:Eclipse Compilation error - Type mismatch;found:Unit required Int in ScalaEclipse 编译错误 - 类型不匹配;发现:Scala 中需要 Int 单位
【发布时间】:2016-07-17 14:18:39
【问题描述】:

我是 scala 的新手,开始在 Eclipse 中编写一些代码。我有三种方法,其中第二种方法抱怨主题中提到的错误

  def add(b:Byte):Unit = sum+=b
  def add1(b:Byte):Int = sum+=b
  def add2(b:Byte):Int = sum

为什么第三种方法没有抱怨,而第二种方法有?我想写的代码尽可能简洁,类似于“将 b 加到总和返回新总和”。所以即使在第二种方法中声明了 Int 的返回类型,为什么 scala 不理解第二种方法中的隐式返回,而它对第三种方法也是如此?

【问题讨论】:

  • 如果要返回sum:def add1(b:Byte):Int ={ sum+=b; sum }
  • @insaan-e - 谢谢你,我明白了!

标签: scala


【解决方案1】:

+= 的返回类型为Unit。所以add1 隐式返回+= 返回的内容,即Unit。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多