【问题标题】:Generic Higher kinded types通用高级类型
【发布时间】:2019-03-04 16:02:34
【问题描述】:
class Toto[F[_]]()
val totos: Seq[Toto[_]] = Seq(new Toto[Future[_]], new Toto[IO[_]])
<console>:12: error: _$1 takes no type parameters, expected: one
val totos: Seq[Toto[_]] = ???
^
我们如何将通配符用于更高种类的类型?
我只想要Seq 或Toto,不管F 是什么。
【问题讨论】:
标签:
scala
types
existential-type
higher-kinded-types
【解决方案1】:
如果您可以将Toto 更改为协变,则以下方法可能有效:
import language.higherKinds
class Toto[+F[_]]()
class Foo[X]
class Bar[X]
val toto: Toto[F] forSome { type F[X] } = new Toto[Foo]
val totos = Seq[Toto[F] forSome { type F[X] }](new Toto[Foo], new Toto[Bar])
感觉类似于this one。
如果这种情况在您的代码中更频繁地发生,您也可以考虑通过将 F 转换为 Toto 的类型成员来将其移开:
import language.higherKinds
class Toto {
type F[X]
}
object Toto {
def empty[A[X]]: Toto = new Toto {
type F[X] = A[X]
}
}
class Foo[X]
class Bar[X]
val totos: Seq[Toto] = Seq(Toto.empty[Foo], Toto.empty[Bar])