为什么在未明确给出 return 类型时,方法 returning Unit 可以被方法 returning String 覆盖?
Why can a method returning Unit be overridden with method returning String when return types are not explicitly given?
我正在研究 Scala Edition1 中编程中的特征一章中的代码示例
https://www.artima.com/pins1ed/traits.html
由于我的错字而遇到了一个奇怪的行为。尽管重写方法的 return 类型与 Unit
和 String
不同,但代码片段下方特征的重写方法不会给出任何编译错误。但是在对象上调用方法时 returns 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 = ()
但是当我在重写的方法中给出显式 return 类型时,它给出了一个编译错误:
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
谁能帮忙解释一下为什么第一种情况没有编译错误
my question is why it got through the compiler in the 1st case
当您没有明确指定 return 类型时,它是由 override
工作所需的类型推断出来的。
原来是Unit
。
由于 String
值(构成函数体的表达式的值)可以分配给 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 Edition1 中编程中的特征一章中的代码示例 https://www.artima.com/pins1ed/traits.html
由于我的错字而遇到了一个奇怪的行为。尽管重写方法的 return 类型与 Unit
和 String
不同,但代码片段下方特征的重写方法不会给出任何编译错误。但是在对象上调用方法时 returns 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 = ()
但是当我在重写的方法中给出显式 return 类型时,它给出了一个编译错误:
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
谁能帮忙解释一下为什么第一种情况没有编译错误
my question is why it got through the compiler in the 1st case
当您没有明确指定 return 类型时,它是由 override
工作所需的类型推断出来的。
原来是Unit
。
由于 String
值(构成函数体的表达式的值)可以分配给 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; () }
.