Private field installer in scala

What is the best way to have a class field in scala read-only outside the class? I understand that I can do something like this:

private var myvalX = 0 // default val def myval = myvalX def myval_=(x: Int) { myvalX = x } 

but I find this extremely ugly due to the _ = operator and the fact that you need to define a separate var whose name is different from the methods. alternatives would be very welcome. thanks!

+4
source share
1 answer

I don’t think it’s good practice for private fields and public users to have the same name. For example, you wrote

 private var myvalX = 0 // default val def myval = myvalX def myval_=(x: Int) { myvalX = x } 

which does not myval ! You probably meant something like

 private def myval_=(x: Int) { myvalX = x } 

which will be read-only. But this is a great example of why this is a bad idea - you are asking for confusion between the public interface and the private implementation details. Other problems that may arise are users who do not understand that value can change from under them, subclasses that override the public getter, without realizing that the private setter is not available, etc.

If you are not trying to share this name, it is clear that there are two things to think about: your basic data and the public interface that relies on this data.

 private var myData = 0 def data = myData 

This is not so bad, is it?

Alternatively, you can use various tricks to make things look a little better if you really insist on using this template. For example, if you have a bunch of fields, you could

 class C { abstract class ReadOnly[A] { def value: A } private class ReadWrite[A](var value: A) extends ReadOnly[A] private implicit def access[A](ro: ReadOnly[A]) = ro.asInstanceOf[ReadWrite[A]] def rw[A](a: A): ReadOnly[A] = new ReadWrite(a) val data = rw(0) val comment = rw("Ho-hum") } 

which allows anything in class C to set data.value and comment.value , and just let everyone else read them. (Edit: change to include all the positive effects in the original example, because if you omit them, you can make mistakes.)

+8
source

All Articles