繁体   English   中英

存在类型的最佳用例

[英]best use cases for existential type

我对存在类型的一些用例感到困惑。 原因是我可以使用显式类型约束来实现相同的结果,所以我的问题是我可以用于scala中存在类型的其他好用例。 这是代码

class A

class C extends A

class Container[T] {

  def take(x: T) = {

  }

}
def doStuff[T <: A](container: Container[T]): Unit = {

}

def doStuff(container: Container[_ <: A]): Unit = {

}

doStuff(new Container[A])
doStuff(new Container[C])

如果我不想使Container变量,因为Container类中的方法参数不应该是T.所以有两种方法来定义doStuff方法来实现一点多态。 一个是参数化方法,另一个是使用存在类型。 两者都有相同的结果,有人可以给我一些只有存在类型可以做的用例,但参数化类型约束或convariant不能这样做。

提前谢谢了。

用例之一:

Scala中的参数多态是谓词和存在类型适用于定义谓词:

// Foo expect that type parameter will be type consctructor for one type param
trait Foo[F[+_]]     

// Boo expect that type parameter will be type consctructor for two type param
trait Boo[F[_,_]]

// Boo expect that type parameter will be type consctructor of type constructor
trait Voo[F[_[_]]]

当然你可以通过类型参数来做到这一点,但在这种情况下你有不必要的类型参数(有时它对于类型推断不是“健康的”):

trait Foo[A, F[A]]
trait Boo[A, B, F[A,B]]
trait Voo[A, B[A], F[B[A]]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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