Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate Scala setters and getters with IntelliJ IDEA

Give the simple class

class MyClass {
  private var myVar: String = _
}

How can I generate the setters and getters for myVar?

The Code | Generate menu shows:

  • Override Methods...
  • Implement Methods...
  • Delegate Methods...
  • Copyright
  • equals() and hashCode()
  • toString()
  • Companion object

IntelliJ version: 14.1.5 OS: OS X 10.10.5

like image 304
ssedano Avatar asked Dec 11 '22 20:12

ssedano


1 Answers

@Zoltán is right - getters and setters are not common in Scala because:

  1. Scala encourages immutability
  2. Scala already generates them for you when make a field - they just aren't named according to the Java beans convention (You can encourage Scala to not generate these methods by being really restrictive in who can see and modify the field - think final private[this] val).
  3. Because of #2, it is possible to go from var someField to private var _someField, def someField = this._someField and def someField_=(value: String) = { this._someField = value } and not have consumers update their code. In other words, the change is source compatible (though I believe it is not binary compatible).

If you need Java bean style getters and setters simply annotate the field with @BeanProperty and scalac will generate the getter and setter for you:

import scala.beans.BeanProperty

class MyClass {
  @BeanProperty
  var myVar: String = _
}

Note that in order to get the is getters and setters for a boolean property you need to use BooleanBeanProperty instead.

like image 84
Sean Vieira Avatar answered Mar 26 '23 07:03

Sean Vieira