gpt4 book ai didi

scala - 向 Symbol 添加更新方法时遇到问题

转载 作者:行者123 更新时间:2023-12-01 05:35:24 24 4
gpt4 key购买 nike

我正在尝试向 Symbol 类添加一个更新方法。

class SymbolUpdate(s: Symbol) {
def update(i: Int) = s.name + i
}
implicit def toSymbolUpdate(s: Symbol) = new SymbolUpdate(s)

但是当我运行代码时,我得到以下信息

scala> 's = 1
<console>:327: error: value update is not a member of object Symbol
's = 1
^

但是当我直接调用该方法时它确实有效。

scala> 's.update(1)
res41: java.lang.String = s1

或者如果我显式地放置一个空参数数组。

scala> 's() = 1
res42: java.lang.String = s1

不确定我的代码有什么问题?

最佳答案

根据Scala Language Spec :

An assignment f(args) = e with a function application to the left of the ‘=’ operator is interpreted as f.update(args, e), i.e. the invocation of an update function defined by f.

看了Programming in Scala中的相应章节就特别清楚了:

Similarly, when an assignment is made to a variable to which parenthesis and one or more arguments have been applied, the compiler will transform that into an invocation of an update methods that takes the arguments in parenthesis as well as the object to the right of the equals sign.

综合起来,我认为它的意思是括号是必需的。

关于scala - 向 Symbol 添加更新方法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11145728/

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