Is there a shorthand for type variable 'm forSome { type m[O] <: UpperBound[O] }` in Scala?

﹥>﹥吖頭↗ 提交于 2021-02-05 08:09:30

问题


Problem:

trait UpperBound[O]
trait High[F[O] <: UpperBound[O]]

def canEqual(that :Any) = that.isInstanceOf[High[_]]

def high(h :High[_]) = ???

Does not compile, because scalac sees the _ type instead of a type constructor it expects. How to fix it, ideally without writing a novel?

Original question (before edits in reply to Dmytro's answer) had:

def canEqual(that :Any) = that.isInstanceOf[High[m forSome { type m[O] <: UpperBound[O] }]]

def high(h :High[m forSome { type m[O] <: UpperBound[O] }] = ???

Is there a shorter way of writing the above two methods by using some wildcard expression? Simply using _ in High's type parameter position doesn't work as the kind doesn't match, and _[_] is not even a valid type expression.


回答1:


  • If you make existential quantization outside High then it's just

    type T = High[F] forSome { type F[O] <: UpperBound[O] }
    
    def canEqual(that: Any) = that.isInstanceOf[T]
    
    def high(h: T) = ???
    
  • If you make existential quantization inside High then since

    implicitly[(n forSome { type n <: Upper}) =:= Upper]
    implicitly[(m[O1] forSome { type m[O] <: UpperBound[O]}) =:= UpperBound[O1]]
    

    (and vice versa) it's just High[UpperBound]

    implicitly[High[m forSome { type m[O] <: UpperBound[O] }] =:= High[UpperBound]]
    
    def canEqual(that: Any) = that.isInstanceOf[High[UpperBound]]
    
    def high(h: High[UpperBound]) = ???
    

    An existential type 𝑇 forSome { 𝑄 } where 𝑄 contains a clause type 𝑡[tps]>:𝐿<:𝑈 is equivalent to the type 𝑇′ forSome { 𝑄 } where 𝑇′ results from 𝑇 by replacing every covariant occurrence of 𝑡 in 𝑇 by 𝑈 and by replacing every contravariant occurrence of 𝑡 in 𝑇 by 𝐿.

    https://scala-lang.org/files/archive/spec/2.13/03-types.html#simplification-rules



来源:https://stackoverflow.com/questions/61041172/is-there-a-shorthand-for-type-variable-m-forsome-type-mo-upperboundo

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