[英]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?
}
}
我期望测试(新的GrandChild)会出现编译错误。 如何运作? 我是否理解类型绑定错误?
由于GrandChild
扩展了Child
因此编译器在调用中选择了B
类型参数作为Child
。
test(new GrandChild)
如果您明确指定类型,则会收到您期望的错误:
test[GrandChild](new GrandChild)
B>:Child表示B应该是Child的超类型,所有这些类都是Parent(Child和GrandChild),因为所有这些类都从Parent扩展而来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.