Why can't you create a setter without getter in scala?

那年仲夏 提交于 2019-12-12 03:37:21

问题


I found in Scala: can't write setter without getter? that you can't create a setter without getter:

The interpretation of an assignment to a simple variable x = e depends on the definition of x. If x denotes a mutable variable, then the assignment changes the current value of x to be the result of evaluating the expression e. The type of e is expected to conform to the type of x. If x is a parameterless function defined in some template, and the same template contains a setter function x_= as member, then the assignment x = e is interpreted as the invocation x_=(e ) of that setter function. Analogously, an assignment f.x = e to a parameterless function x is interpreted as the invocation f.x_=(e ). 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 .

So it is a design decision to not allow setters without getters. But why? Is it just be harder to implement or is it fundamentally impossible to do?

I do have a valid use case for it, using it as a (somewhat complex) setter, where not using this syntactic sugar would break having the same syntax everywhere in the project.


回答1:


You might try this to exclude the accessor from your API:

scala> class C { def c_=(i: Int) = println(i) ; private def c: Int = ??? }
defined class C

scala> val c = new C
c: C = C@289fdb08

scala> c.c = 42
<console>:14: error: method c in class C cannot be accessed in C
val $ires0 = c.c
               ^
<console>:12: error: method c in class C cannot be accessed in C
       c.c = 42
         ^

scala> def f = { c.c = 42 ; 0 }
<console>:12: error: method c in class C cannot be accessed in C
       def f = { c.c = 42 ; 0 }
                   ^

In the first error, the REPL is trying to report the value by using the accessor.

This notion of paired accessor and mutator is called the universal access principle, so that accessed member looks like a property.

The expression c.c must type-check before further desugaring. Otherwise, the transform (to an invocation of c.c_=) must be purely syntactic.

For example, an implicit conversion that supplies an extension method c_= could come into play.



来源:https://stackoverflow.com/questions/39134978/why-cant-you-create-a-setter-without-getter-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!