gpt4 book ai didi

scala - 你能在 Scala 中返回一个可赋值的左值吗?

转载 作者:行者123 更新时间:2023-12-04 17:53:33 25 4
gpt4 key购买 nike

(注意,左值实际上是 C 语法中的一个术语,我不知道它在 Scala 中叫什么!)

正在尝试学习 Scala...今晚我正在为一种动态范围语言的内部 DSL 工作,该语言可能类似于 PHP 语法。

我的 REPL 是:欢迎使用 Scala 版本 2.7.6.final(Java HotSpot(TM) Client VM,Java 1.6.0)。

我有一些虚构的示例代码:

类 $(任何:任何){
def update(sym: Symbol, any: Any) { println("第 2 行执行");}
def ->(sym: Symbol) : $ = { println("第 1 行执行");返回这个}
def update(any: Any) { println("第 3 行执行");}
}

以下按预期工作:

Scala> var a = new $(0)
a: $ = $@19238ad

Scala> a('x) = "等等"
第 2 行执行

另一方面,为什么以下不调用 1 参数更新方法?

标量> a = 1
:6: 错误:类型不匹配;
发现:整数(1)
要求:$
一 = 1
^

在进行一些试验和错误时,我发现了这种语法上的好奇:

Scala> class A { def this_= { print("hello") } }
定义类 A

Scala> var a = new A
a: A = A@9aca82

标量> a = 2
:6: 错误:类型不匹配;
发现:整数(2)
要求:A
一 = 2
^

Scala> a.this_
:7: 错误:值 this_ 不是 A 的成员
在他的_
^

覆盖上面的“this_”是什么意思?它去哪里?

最终,我希望这个工作:

a->'x = "等等"

谢谢

最佳答案

def this_= { print("hello") }

你似乎认为这是方法 this_等于 { print("hello") } .相反,这是方法 this_= ,它使用过程样式声明(即,没有等号)。

它最常使用如下:
scala> class A {
| private var _x = ""
| def x = _x
| def x_=(s: String) = _x = s.toUpperCase
| }
defined class A

scala> new A
res0: A = A@1169fb2

scala> res0.x
res1: java.lang.String =

scala> res0.x = "abc"

scala> res0.x
res2: java.lang.String = ABC

但是,虽然您巧合地使用了具有特殊含义的语法 ( id_= ),但它只是一个标识符。任何标识符都混合了字母数字字符和其他符号,由下划线字符分隔。

最后,不,Scala 中没有可赋值的左值。你可以有这样的事情:
id(key) = value // with update
id.key = value // with key_=, as long as key also exists and is public
id += value // or any other method containing "=" as part of its name

例如,你可以这样做:
scala> class A {
| private var _x = ""
| def :=(s: String) = _x = s.toUpperCase
| override def toString = "A("+_x+")"
| }
defined class A

scala> val x = new A
x: A = A()

scala> x := "abc"

scala> x
res4: A = A(ABC)

但是 = ,本身是保留的。而且,顺便说一下,Scala 中没有按引用传递——您永远无法更改作为参数传递的变量的值。

关于scala - 你能在 Scala 中返回一个可赋值的左值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2641886/

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