gpt4 book ai didi

scala - 当混合具有冲突的抽象覆盖的多个特征时,我如何预测将选择哪个实现?

转载 作者:行者123 更新时间:2023-12-01 23:54:44 25 4
gpt4 key购买 nike

考虑这个例子:

abstract class Writer {
def write(message: String): Unit
}

trait UpperCaseFilter extends Writer {
abstract override def write(message: String) =
super.write(message.toUpperCase)
}

trait LowerCaseFilter extends Writer {
abstract override def write(message: String) =
super.write(message.toLowerCase)
}

class StringWriter extends Writer {
val sb = new StringBuilder

override def write(message: String) =
sb.append(message)

override def toString = sb.toString
}

object Main extends App {
val writer = new StringWriter with UpperCaseFilter with LowerCaseFilter
writer.write("Hello, world!")
println(writer)
}

我对输出“HELLO, WORLD!”感到惊讶为什么输出不是“hello, world!”还是编译错误?

最佳答案

决定它的逻辑叫做线性化。您可以在此处找到有关它的更多信息:

http://www.artima.com/pins1ed/traits.html#12.6

在您的情况下,整个类层次结构将像这样线性化:

LowerCaseFilter > UpperCaseFilter > Writer > StringWriter > AnyRef > 任何

因此,如您所见,UpperCaseFilter 是进入 StringWriter 的最后一个转换。

关于scala - 当混合具有冲突的抽象覆盖的多个特征时,我如何预测将选择哪个实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24561914/

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