For example, I have the following class
class Person(val name: String) { }
Some code use this class invoking constructor with named parameters
val person = new Person(name = "Smith")
println(person.name)
I need to add a custom accessor for property name
without braking code like above. So approach with renaming a constructor parameter does not suite me
class Person(val _name: String) {
def name = {
println("custom action")
_name
}
}
Is there any other way? If no, does it mean that for new classes I always should manually make custom accessors to ensure encapsulation?
You can make your primary constructor private and add some extra value to it to prevent ambiguity.
class Person private (_name: String, dummy: Unit) {
def this(name: String) = this(name, ())
def name: String = {
println("custom action")
_name
}
}
new Person(name = "John").name // will print "custom action"
It's hacky, but I'll prefer that over Java maybe-I'll-need-it-later style accessors
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.