scala - 如何修复 Scala (2.11) 中路径相关类型的类型不匹配错误?
问题描述
我有这样的代码
trait Toy
trait Child {
type T <: Toy
def toys : Seq[T]
def play(toys: Seq[T]): Unit
}
trait Parent {
type C <: Child
def firstChild: C
}
trait Home {
def parent: Parent
def toys: Seq[Parent#C#T]
def apply() = {
val ts = toys
parent.firstChild.play(toys)
}
}
但我无法编译它:
[error] .../module/common/src/main/scala/test/Debug.scala:21:32: type mismatch;
[error] found : Seq[test.Parent#C#T]
[error] required: Seq[_12.T] where val _12: test.Parent#C
[error] parent.firstChild.play(toys)
有没有办法在不将所有抽象类型转换为参数类型的情况下修复此错误?
解决方案
使其编译的一种方法是:
trait Toy
trait Child {
type T <: Toy
def toys : Seq[T]
def play(toys: Seq[T]): Unit
}
trait Parent { parent =>
type C <: Child
val firstChild: C
}
trait Home {
val parent: Parent
def toys: Seq[parent.firstChild.T]
def apply() = {
val ts = toys
parent.firstChild.play(toys)
}
}
请记住,类型成员绑定到它们的外部实例。如果您给孩子一个玩具,它必须是专门为该特定父母的特定孩子设计的玩具 ( parent.firstChild.T
),而不是任何潜在父母 ( Parent#C#T
) 的任何潜在孩子。
推荐阅读
- algorithm - 埃及乘法算法复杂度?
- visual-studio-code - VScode SSH扩展卡在安装步骤
- python - socket.gethostbyaddr 在本地主机上使用时会引发错误
- css - CSS:文本渐变后面的线
- javascript - 如何为所有命令的特定用户进行冷却(Discord.js)
- javascript - 在 Jest 测试期间,Process.env 变量在函数之外不可用
- django - 模板无法访问 Django 收集的静态文件
- java - 是否有任何有效的微优化来找到唯一网格路径的数量?
- angular - 基于键值的角度更改ngClass
- java - 用户界面中的 JTable