1

我試圖創建與依賴類型_ >: a.type相關的類型別名。爲什麼Scala編譯器禁止將通配符類型聲明爲類型參數的超類型

Scala編譯器報告,我不明白的錯誤:

scala> def foo[A](a: A) = { 
    | type F = Function1[_ >: a.type, Unit] 
    | } 
<console>:12: error: type mismatch; 
found : a.type (with underlying type A) 
required: AnyRef 
Note that A is unbounded, which means AnyRef is not a known parent. 
Such types can participate in value classes, but instances 
cannot appear in singleton types or in reference comparisons. 
     type F = Function1[_ >: a.type, Unit] 
           ^

如果我更換a: Aa: A with AnyRef,它的工作原理:

scala> def foo[A](a: A with AnyRef) = { 
    | type F = Function1[_ >: a.type, Unit] 
    | } 
foo: [A](a: A with AnyRef)Unit 

爲什麼? 限制的目的是什麼?

回答

5

參見:http://docs.scala-lang.org/sips/pending/42.type.html

任何VS AnyRef

目前有在某些情況下使用單種的可能性,但僅限於標識其指向符合AnyRef恆定。這個限制是由於任何沒有eq方法,這是什麼用於單體類型相等檢查和模式匹配https://github.com/scala/scala/pull/3558。郵件列表herehere已經討論過這個問題,並且同意這需要完成。

+0

我還是不明白它爲什麼會影響_>:a.type。我認爲像_>:a.type這樣的存在類型永遠不會涉及類型相等檢查。 –

+0

我假設應用保護措施時不考慮上下文;讓我們希望斯卡拉語言大師之一將澄清。 – devkat

相關問題