Scala 我在使用存在类型时出错
我在做一些关于存在主义类型的实验。首先,我定义了一个小类层次结构:Scala 我在使用存在类型时出错,scala,Scala,我在做一些关于存在主义类型的实验。首先,我定义了一个小类层次结构: trait Fruit case class Apple extends Fruit case class Banana extends Fruit 然后我想要一套可以添加不同类型水果的装置: val set1: Set[_ >: Fruit] = Set() // Which is equivalent to: val set2: Set[F] forSome { type F >: Fruit } = Set(
trait Fruit
case class Apple extends Fruit
case class Banana extends Fruit
然后我想要一套可以添加不同类型水果的装置:
val set1: Set[_ >: Fruit] = Set()
// Which is equivalent to:
val set2: Set[F] forSome { type F >: Fruit } = Set()
// This compiles
set1 += Apple()
set1 += Banana()
set2 += Apple()
set2 += Banana()
到目前为止,一切顺利。但是现在我想要一组函数,从一些水果到单元:
// This still compiles
val set3: Set[(_ <: Fruit) => Unit] = Set()
// But this doesn't
val set4: Set[F => Unit] forSome { type F <: Fruit } = Set()
为什么会这样?代码中有一些错误:
val set4: Set[F => Unit] forSome { type F <: Fruit } = Set()
原因很简单。从=
的左侧定义类型和变量名,从右侧调用类型构造函数和类构造函数。您试图用未定义的值调用类型构造函数,但需要构造最终类型,这是错误的原因。代码中有错误:
val set4: Set[F => Unit] forSome { type F <: Fruit } = Set()
原因很简单。从
=
的左侧定义类型和变量名,从右侧调用类型构造函数和类构造函数。您试图用未定义的值调用类型构造函数,但需要构造最终类型,这是一个错误原因。哦,我想我现在理解了,但区别非常细微。最后一个问题呢?为什么我不能使用存在类型来参数化赋值右边的函数呢?哦,我想我现在明白了,但差别真的很微妙。最后一个问题呢?为什么我不能使用存在类型来参数化赋值右侧的函数?
val set4: Set[(F => Unit) forSome { type F <: Fruit }] = Set()
//OR:
val set4: Set[Function1[F,Unit] forSome { type F <: Fruit }] = Set()
val set1 = Set[_ >: Fruit]()