Functional Objects

  • If a class doesn’t have body, you don’t need to have curly brackets
  • The Scala compiler will compile any code you place in the class body, which isn’t part of a field or a method definition, into the primary constructor. For example, you could print a debug message like this:
class Rational(n: Int, d: Int) {
     println("Created "+ n +"/"+ d)
  • The override modifier in front of a method definition signals that a previous method definition is overridden
  • A precondition is a constraint on values passed into a method or constructor, a requirement which callers must fulfil. One way to do that is to use require:
class Rational(n: Int, d: Int) {
    require(d != 0)
    override def toString = n +"/"+ d
  • Sometimes you need multiple constructors in a class. In Scala, constructors other than the primary constructor are called auxiliary constructors. Auxiliary constructors in Scala start with def this(…). In Scala, every auxiliary constructor must invoke another constructor of the same class as its first action. In other words, the first statement in every auxiliary constructor in every Scala class will have the form “this(…)”. The invoked constructor is either the primary constructor or another auxiliary constructor that comes textually before the calling constructor. The net effect of this rule is that every constructor invocation in Scala will end up eventually calling the primary constructor of the class. The primary constructor is thus the single point of entry of a class.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s