Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use property on Scala?

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.

like image 870
Phương Nguyễn Avatar asked Dec 04 '22 12:12

Phương Nguyễn


2 Answers

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
like image 110
missingfaktor Avatar answered Jan 02 '23 17:01

missingfaktor


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.

like image 33
Dean Wampler Avatar answered Jan 02 '23 17:01

Dean Wampler