scala - 当未明确给出返回类型时,为什么可以用返回 String 的方法覆盖返回 Unit 的方法?

标签 scala overriding traits

我正在研究 Scala 版编程中的特征一章中的代码示例
https://www.artima.com/pins1ed/traits.html

由于我的错字,遇到了一个奇怪的行为。尽管覆盖方法的返回类型不同 Unit 尽管覆盖以下代码片段的特征的方法不会产生任何编译错误对比 String .但是在对象上调用该方法时,它返回 Unit 但不打印任何内容。

trait Philosophical {
    def philosophize = println("I consume memory, therefore I am!")
}

class Frog extends Philosophical {
  override def toString = "green"
  override def philosophize = "It aint easy to be " + toString + "!"
}

val frog = new Frog
//frog: Frog = green

frog.philosophize
// no message printed on console

val f = frog.philosophize
//f: Unit = ()

但是当我在被覆盖的方法中给出显式返回类型时,它给出了一个编译错误:
class Frog extends Philosophical {
  override def toString = "green"
  override def philosophize: String = "It aint easy to be " + toString + "!"
}
         override def philosophize: String = "It aint easy to be " + toString +
                      ^
On line 3: error: incompatible type in overriding
       def philosophize: Unit (defined in trait Philosophical);
        found   : => String
        required: => Unit

任何人都可以帮助解释为什么在第一种情况下没有编译错误。

最佳答案

当预期类型为 Unit 时, any value can be accepted :

Value Discarding

If e has some value type and the expected type is Unit, e is converted to the expected type by embedding it in the term { e; () }.

关于scala - 当未明确给出返回类型时,为什么可以用返回 String 的方法覆盖返回 Unit 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59139519/

相关文章:

php - Laravel/Eloquent 建议覆盖特征属性?

Scala案例类翻倍

android - 在 Android 上使用 Scala 值得吗?有很多开销吗?问题?

ios - Swift 属性观察不会覆盖

css - 用@import 覆盖 css 样式不起作用

scala - 继承消息处理行为

php - 如何使用特征 - Laravel 5.2

scala - 什么会导致阶段在 Spark 中重新尝试

scala - 无形 : Checking of the Type Constraints of Polymorphic Functions (lifted types)

iphone - 覆盖对多关系的核心数据设置方法