Yes, you can set a property name by setName and get it by getName. But what about property like this in C#:
int Name{
get{return name;}
set{name = value;}
}
or
Name{get; set;}
(auto property)
I wonder if such thing exists in Scala. Googling around without any signals.
scala> class A {
| var name: String = ""
| }
defined class A
scala> val a = new A
a: A = A@1df3082
scala> a.name = "kool"
scala> a.name
res0: String = kool
scala> class A {
| private var _name = ""
| def name = _name // a getter
| def name_=(value: String) { // a setter
| _name = value
| }
| }
defined class A
scala> val a = new A
a: A = A@baf4ae
scala> a.name = "abc"
scala> a.name
res1: java.lang.String = abc
Just for completeness, if you only want immutable fields (recommended!)
case class A(name: String)
is the same thing as
class A(val name: String)
with regards to immutable fields/properties. The "case" keyword automatically makes the constructor arguments vals, as well as adding other goodies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With