I am little confused about some use cases of existential types. The reason is that I can use explicit type constraints to achieve same result, so my question is there other good use cases I can use for existential types in scala. Here is code
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])
If I dont want to make Container convariant, because the parameter of method in Container class shouldnt be T. so there are 2 ways to define doStuff methods to achieve a little polymorphism. One is a parameterized method, the other one is using existential type. Both have the same result, can someone give me some use cases that only existential types can do but parameterized type constraint or convariant cannot do it.
Many thanks in advance.
One of use-cases:
Parametric polymorphism in Scala is predicave and existential types is good for define predicates:
// 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[_[_]]]
of course you can do that by type parameters but in this case you have unnecessary type parameters (sometimes it isn't "healthy" for type inference):
trait Foo[A, F[A]]
trait Boo[A, B, F[A,B]]
trait Voo[A, B[A], F[B[A]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With