gpt4 book ai didi

scala - 修复 self 类型中的抽象类型

转载 作者:行者123 更新时间:2023-12-01 12:58:02 26 4
gpt4 key购买 nike

考虑一下:

object TypeProblem {

trait A {
type T
val set = Set[T]()
}

trait B {
def b()
}

trait FooBad { this: A =>
type T <: B
def x {
set.foreach(_.b())
}
}

trait FooOk { this: A =>
type MyT <: B
type T = MyT

def x {
set.foreach(_.b())
}
}

}

编译器提示值 b 不是 FooBad.this.T 的成员那么为什么 FooOk 在我定义新类型 MyT 并将 T 分配给 MyT 的地方工作?

最佳答案

FooBad 的自身类型被编译器扩展为 FooBad with A(这样您仍然可以访问您自己定义的成员)。这意味着 T 获得了 A 中的定义,而不是您所期望的 FooBad 中的定义。您可以通过更改 FooBad 的定义来明确添加您自己的类型来修复您的代码:

trait FooBad { this: A with FooBad =>
..
}

或者通过使用子类化更好

trait FooBad extends A {
..
}

我相信在大多数情况下, self 类型应该被简单的子类化所取代。它更容易理解,不那么可怕,并且可以实现更好的封装。

关于scala - 修复 self 类型中的抽象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8559437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com