gpt4 book ai didi

scala - 使用 mixin trait 丰富对象

转载 作者:行者123 更新时间:2023-12-05 06:42:08 28 4
gpt4 key购买 nike

我有以下结构:

trait Runner {
def run: Unit
}

trait LoggableRunner extends Runner {
abstract override def run {
println("logging enter")
super.run
println("logging exit")
}
}

class RealRunner extends Runner {
def run = println("running...")
}

这样我就可以通过以下方式登录来丰富我的类(class):

val a = new RealRunner with LoggableRunner

在运行 run 方法之前和之后添加日志信息。

现在我真正想要的是能够用 traits 组合 scala 对象。我试过同样的方法:

object RealRunner extends LoggableRunner{
def run = println("running...")
}

但我得到:method run needs override modifier

所以我尝试了:

 object RealRunner extends LoggableRunner{
override def run = println("running...")
}

但我得到:method run needs abstract override modifiers。所以我再次尝试添加抽象,我得到:abstract override modifier only allowed for members of traits

甚至可以将特征混合到对象中吗?

最佳答案

我不确定为什么它会这样(确实看起来很奇怪和令人困惑,希望有更多线索的人会介入,并对此给出一些理由),但这是你可以做你想做的事的方法:

trait Runner {
def run = () // making it non-abstract, makes things a lot easier!
}

trait LoggableRunner extends Runner {
override def run = {
println("start")
super.run
println("stop")
}
def foo = "foo"
}

trait RealRunner extends Runner { self: LoggableRunner =>
override def run = println(foo) // uses things from LoggableRunner
}

object RealRunner extends RealRunner with LoggableRunner

scala> RealRunner.run
start
foo
stop

哇哦!

关于scala - 使用 mixin trait 丰富对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38393612/

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