简体   繁体   中英

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. 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

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扩展而来。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM