views:

135

answers:

3

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.

+5  A: 
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
missingfaktor
+2  A: 

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.

Dean Wampler
+2  A: 

You can use scala.reflect.BeanProperty if you want java get/set methods

class Person {
   @scala.reflect.BeanProperty
   private var name: String = _
}

val p = new Person
p.setName("Peter")
println(p.getName)
jgoday