我一直在阅读 Dotty,因为它看起来即将成为 scala 3,并注意到类型投影被认为是“不健全的”并从语言中删除......
这看起来很糟糕,因为我已经看到了几个真正有用的用例。例如:
trait Contents
class Foo extends Contents
class Bar extends Contents
trait Container[T <: Contents] { type ContentType = T }
class FooContainer extends Container[Foo]
class BarContainer extends Container[Bar]
trait Manager[T <: Container[_]] {
type ContainerType = T
type ContentType = T#ContentType
def getContents: ContentType
def createContainer(contents: ContentType): ContainerType
}
如何在 Dotty 中做这样的事情?添加第二个类型参数到Manager
? 但是,除了它使创建和操作 的实例变得非常乏味之外Manager
,它也不太有效,因为没有办法强制这两种类型之间的关系(Manager[FooContainer, Bar]
不应该是合法的)。
然后,还有其他用途,如 lambda 类型和部分应用类型,它们对于创建有偏函子等很有用……或者这些(部分应用类型)是否成为 Dotty 中的“一等公民”?
编辑
为了回答评论中的问题,这里有一个他可以使用的有点做作的例子。假设,我Managers
实际上是 Akka Actors
:
abstract class BaseManager[T <: Container[_]](
val storage: ContentStorage[T#ContentType]
) extends Actor with Manager[T] {
def withContents(container: T, content: ContentType): ContainerType
def withoutContents: T
var container: T = withoutContents
def receive: Receive {
case ContentsChanged =>
container = withContents(container, storage.get)
case ContainerRequester =>
sender ! container
// ... other common actions
}
}
class FooManager(storage: FooStorage) extends BaseManager[FooContainer](storage) {
def withContents(container: FooContainer, content: Foo) =
container.copy(Some(content))
def withoutContent = FooContainer(None)
override def receive: Receive = super.receive orElse {
// some additional actions, specific to Foo
}
}
case class FooContainer(content: Option[Foo]) extends Container[Foo]{
// some extremely expensive calculations that happen when
// content is assigned, so that we can cache the result in container
}