我正在研究 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 isUnit
,e
is converted to the expected type by embedding it in the term{ e; () }
.
关于scala - 当未明确给出返回类型时,为什么可以用返回 String 的方法覆盖返回 Unit 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59139519/