首页 > 解决方案 > 如何修复 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)

有没有办法在不将所有抽象类型转换为参数类型的情况下修复此错误?

标签: scala

解决方案


使其编译的一种方法是:

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) 的任何潜在孩子。


推荐阅读