private field setter in scala -


what best way have class field in scala read-only outside of class? realize can this:

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

but find extremely ugly due _= operator , fact need define separate var name different methods. alternatives welcome. thank you!

i don't think it's practice have private fields , public ones share same name. example, wrote

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

which doesn't make myval read-only @ all! meant like

private def myval_=(x: int) { myvalx = x } 

which read-only. perfect example of why it's bad idea--you asking confusion between public interface , private implementation details. other problems can arise users not realizing value might change out under them, subclasses redefining public getter without realizing private setter not available, , on.

if don't try share name, it's clearer there 2 things think about: underlying data, , public interface relies upon data.

private var mydata = 0 def data = mydata 

that's not bad, it?

alternatively, can use various tricks make things nicer if insist on using pattern. example, if have bunch of fields could

class c {   abstract class readonly[a] { def value: }   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 let in class c set data.value , comment.value, , let else read them. (edit: modified include goodies in original example, since if omit them might make errors.)


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -