gpt4 book ai didi

scala - 如何使 "this"隐式?

转载 作者:行者123 更新时间:2023-12-02 03:31:48 28 4
gpt4 key购买 nike

我有一个类实例,应该在此类的方法中隐式传递该实例。像这样:

class Game(player: Player) {
protected implicit val implicitThis = this // This is the workaround I use now

def play = player.makeMove() // makeMove takes an implicit game: Game
}

最佳答案

你可以把它打包成一个trait。

trait ImplicitMe {
protected implicit def implicitMe: this.type = this
}

class Game extends ImplicitMe {
private def foo(implicit g: Game) = g
def bar = foo
}

(可能还想在特征上添加 @inline。)

关于scala - 如何使 "this"隐式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26200223/

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