Classes · 34 of 42

Classes - continued

Uniform Access

  • Scala’s getters and setters use the principle of uniform access, e.g. if you change the implementation of a field declared var name to a method def name you will not need to recompile the code
  • Therefore there can’t be a variable or method (def, val or var, private or public) that has the same name in a class

Java style getters and setters

  • Scala’s automatic getters and setters follow the uniform access principle, so the getter and setter name is the same as the field it encapsulates
  • However if you need to have Java client code accessing your Scala class, it’s as easy as adding a @BeanProperty annotation to instruct the compiler to automatically add a Java bean style getter and setter.
  • Note that in Scala 3 the generated getName()/setName(...) exist for Java callers; Scala code keeps using the uniform accessors (sp.name)
  • For boolean properties of style isFlag use @BooleanBeanProperty instead
//A full Java boilerplate style class (not idiomatic Scala!)
class JPerson() {
  var _name: String = null
  def this(_name:String) = {
    this()
    this._name = _name
  }
  //Scala style getters and setters
  def name_=(_name:String) = this._name = _name
  def name = this._name

  //Java style getters and setters
  def getName() = name
  def setName(name:String) = this.name = name
}

//Which can be generated in 1 line of idiomatic Scala
import scala.beans.*
class SPerson(@BeanProperty var name:String)
//Note: @BeanProperty is optional
//(only if you need Java code to call getName()/setName:
// the generated bean methods are for Java interop; from
// Scala you use the uniform accessors below)

val jp = new JPerson("Java Style")
val sp = new SPerson("Scala Style")

println(jp.name)
println(sp.name)

jp.name += " sucks!"
sp.name += " rocks!"

println(jp.getName())
println(sp.name)

Contents

Scala basics

  1. Overview
  2. Scalculator
  3. Operators are methods
  4. Variables
  5. Final variables
  6. Printing values
  7. String interpolation
  8. String formatting
  9. Useful operations
  10. Method definition
  11. Method definition 2
  12. Method definition 3
  13. Anonymous functions
  14. Anonymous functions 2
  15. Return multiple values
  16. Declare multiple variables
  17. Assign multiple variables
  18. Loops using while
  19. Loops using for
  20. Loops without loops
  21. If
  22. Match as a switch
  23. Arrays
  24. Lists
  25. Sets
  26. Maps
  27. Mutable collections
  28. Collections: accessing elements
  29. Collections: concatenation
  30. Mutable collection operations
  31. Immutable collections with var
  32. Collections: useful methods
  33. Classes
  34. Classes, continued

What's new in Scala 3

  1. Scala 3: what changed
  2. Optional braces & new control syntax
  3. Top-level definitions & @main
  4. Enums & ADTs
  5. Extension methods
  6. given & using
  7. Union & intersection types
  8. Smaller niceties