簡體   English   中英

上型界限和下型界限的混淆

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM