This is a note collecting key concepts involved in Scala.

Module

Module is a way to organize different parts to enable programming in the large. Scala uses an object to represent a module. If there are multiple implementations of a module, then define an abstract class as the module’s parent. Use abstract class in dependency declaration. Then let the object (an actual implementation) inherit from the abstract class – assign actual implementation to the dependent abstract class.

However, module is usually big. At both the abstract class level and the object level, use trait to divide responsibilities. A self-type can help to link traits together: a trait use this: A=> to make it use another trait’s member. It can be multiple traits in self reference: this: A with B =>.

Sometime, to aovid compiler error, use singleton type to explicitly specify the type.

The modules can be linked during runtime with configuration code.

object, class, trait

An object extends a class constructor to create an instance of the the class. Therefore, it is common to use an object as a member or a method parameter in trait.

1
2
3
4
5
abstract class Food(val name: String) {
  override def toString = name
}

object Apple extends Food("Apple)

A sequence of case in curly braces is a partial function. A case sequence is a function literal, only more general in a sense that it has multiple entry points.

New Control Structure

Scala let you use {}, instead of () to pass an argument to a function that has only one parameter. It is helpful to write functional literal in the block to make the funciton looks like a DSL.

If a function takes a single parameterless function, you can use by-name parameter: a type like => type. By-name parameter is only evaluated inside a function body when it is used.

If a parameter is a by-name parameter, a code block (expressions inside {}) is often used.

Trait

Traits encapesualte fields and method and is mixed into classes. A trait defines a type. A trait is similar to a class in the sense that it can have fields and methods. However, it can have type parameter but cannot have trait (similar to class) parameters. Its super is dynamicly bound to a super class to enable stackable modification. Use the trait only modifier combination abstract override to stack modification. A trait mixed into a class is called a mixin. The order of multiple mixins are right first due to the trait linearization.

To choose between a trait, a class or and an abstract class:

  • If a bahavior is not reused, use a concrete class.
  • If a bahavior is used by multiple unrelated classes, use trait as a minxin.
  • If a bahavior is distributed as a compiled package, use an abstract class. Any change to a trait requires a recompilation of all classes that mix the trait.
  • If you have no idea, start with a trait.

Scala import can import package, object or an instance. It supports renaming. oldName => newName or discarding a name oldName => _.