[英]Confusion in upper type bound and lower type bound
*/
class Parent
class Child extends Parent
class GrandChild extends Child
object main{
def test[B >: Child](x : B) = x; // B should be of type Child or Parent
def main(args: Array[String]): Unit = {
test(new Parent); //works. B == Parent
test(new Child); //works. B == Child
test (new GrandChild) // works!!! Surprise!!! B == GrandParent. This should not work, right?
}
}
I was expecting that test (new GrandChild) should give compilation error. 我期望测试(新的GrandChild)会出现编译错误。 How is it working?
如何运作? Am I understanding type bound wrongly?
我是否理解类型绑定错误?
Since GrandChild
extends Child
the compiler has chosen B
type parameter to be Child
in the invocation 由于
GrandChild
扩展了Child
因此编译器在调用中选择了B
类型参数作为Child
。
test(new GrandChild)
if you specify the type explicitly you get the error you expect: 如果您明确指定类型,则会收到您期望的错误:
test[GrandChild](new GrandChild)
B>:Child表示B应该是Child的超类型,所有这些类都是Parent(Child和GrandChild),因为所有这些类都从Parent扩展而来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.