你能在Scala中返回一个可赋值的左值吗?
发布时间:2020-12-16 09:52:11 所属栏目:安全 来源:网络整理
导读:(注意,左值实际上是C语法中的一个术语,我不知道它在 Scala中的名称是什么!) 试着学习Scala ……今晚我正在研究内部DSL上的动态范围语言,可能类似于PHP语法. 我的REPL是:欢迎使用Scala版本2.7.6.final(Java HotSpot(TM)客户端VM,Java 1.6.0). 我有一些简化
(注意,左值实际上是C语法中的一个术语,我不知道它在
Scala中的名称是什么!)
试着学习Scala ……今晚我正在研究内部DSL上的动态范围语言,可能类似于PHP语法. 我的REPL是:欢迎使用Scala版本2.7.6.final(Java HotSpot(TM)客户端VM,Java 1.6.0). 我有一些简化的示例代码: class $(any: Any) { def update(sym: Symbol,any: Any) { println("line 2 executed");} def ->(sym: Symbol) : $= { println("line 1 executed"); return this } def update(any: Any) { println("line 3 executed");} } 以下按预期工作: scala> var a = new $(0) a: $= $@19238ad scala> a('x) = "blah" line 2 executed 另一方面,为什么以下不调用1参数更新方法? scala> a = 1 :6: error: type mismatch; found : Int(1) required: $ a = 1 ^ 在做一些试验和错误时,我发现了这种语法上的好奇心: scala> class A { def this_= { print("hello") } } defined class A scala> var a = new A a: A = A@9aca82 scala> a = 2 :6: error: type mismatch; found : Int(2) required: A a = 2 ^ scala> a.this_ :7: error: value this_ is not a member of A a.this_ ^ 覆盖上面的“this_”有什么意义?它去哪儿了? 最终,我希望这个工作: a->'x = "blah" 谢谢 解决方法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中没有通过引用传递 – 您将永远无法更改作为参数传递的变量的值. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |