“can't existentially abstract over parameterized type…”

£可爱£侵袭症+ 提交于 2019-11-29 09:24:12

My hunch would be that this is because due to the following statements in the spec, § 6.11 , blocks:

A locally defined type definition type t = T is bound by the existential clause type t >: T <: T . It is an error if t carries type parameters.

And a structural instance creation expression is evaluated to a block, so


new {def greet{println("hello")}}

is a shorthand for


{ class anon$X extends AnyRef{ def greet = println("hello") }; new anon$X }

so it evaluates to a block expression (according to § 6.10 of the spec), with the aforementioned restriction. Why this restriction is there I do not know, however. The error that is thrown can be found in the Typers class at this location, which seems to confirm that this restriction is the cause of the error that you see. As you mentioned, encoding the function in a class removes the block expression restriction:


scala> class N[M[_]]
defined class N

scala> class Q { def as[M[_]](n:N[M]) = null}
defined class Q

scala> new { def as[M[_]](n:N[M]) = null}       
:7: error: can't existentially abstract over parameterized type M
       new { def as[M[_]](n:N[M]) = null}

To me this sounds like a simplicity against generality case: there could be a new type variable generated every time a block is created capturing some type constructor instantiated with existential type, but that would make error diagnostics more difficult to understand.

Also note that having a class turns the call into a fast INVOKEVIRTUAL, rather than invoking as() method by reflection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!