Tuesday, 10 September 2013

How to create a Scala class with private field with public getter, and primary constructor taking a parameter of the same name

How to create a Scala class with private field with public getter, and
primary constructor taking a parameter of the same name

Search results so far have led me to believe this is impossible without
either a non-primary constructor
class Foo { // NOT OK: 2 extra lines--doesn't
leverage Scala's conciseness
private var _x = 0
def this(x: Int) { this(); _x = x }
def x = _x
}
val f = new Foo(x = 123) // OK: named parameter is 'x'`
or sacrificing the name of the parameter in the primary constructor
(making calls using named parameters ugly)
class Foo(private var _x: Int) { // OK: concise
def x = _x
}
val f = new Foo(_x = 123) // NOT OK: named parameter should be 'x'
not '_x'
ideally, one could do something like this:
class Foo(private var x: Int) { // OK: concise
// make just the getter public
public x
}
val f = new Foo(x = 123) // OK: named parameter is 'x'
I know named parameters are a new thing in the Java world, so it's
probably not that important to most, but coming from a language where
named parameters are more popular (Python), this issue immediately pops
up.
So my question is: is this possible? (probably not), and if not, why is
such an (in my opinion) important use case left uncovered by the language
design? By that, I mean that the code either has to sacrifice clean naming
or concise definitions, which is a hallmark of Scala.
P.S. I would also like to ask the reader to consider the case where a
public field needs suddenly to be made private, while keeping the getter
public, in which case the developer has to change 1 line and add 3 lines
to achieve the effect while keeping the interface identical:
class Foo(var x: Int) {} // no boilerplate
->
class Foo { // lots of boilerplate
private var _x: Int = 0
def this(x: Int) { this(); _x = x }
def x = _x
}

No comments:

Post a Comment