This page dicusses the Scala language and its object structure.
In Scala everything is an object, including numbers, so an expression like 1+2 is evaluated by a method call on the number '1' as follows:
1.+(2)
Scala classes are either:
- value classes - inherits from scala.AnyVal
- reference classes - inherits from scala.AnyRef (equivilant to java.lang.Object).
Functions
Functions are also objects, we can pass a function (instanciated method) to another method as shown here:
def eventReporter( callback: () =>unit) { ... callback() ... }
where we pass the function to eventReporter which then calls the function.
The parameter 'callback: () =>unit' says pass a function with no parameters which returns the type 'unit'.
Objects
- Objects are static
- Classes are dynamic
Objects have 2 special methods:
- apply - Treats myObject(myTuple) as if you had typed myObject.apply(myValue)
- unapply - in a case statement, if the myObject(myTuple) between case and => matches then call the unapply method of myObject.
For example in this:
value match { case myObject(param1,param2) => println("this is called ") }
if value matches myObject(param1,param2) then myObject.unapply(value:myObject) gets called.
Case Classes
When case classes are created like:
abstract class SExpression
case class SString(sstring:String) extends SExpression
case class SSymbol(ssymbol:String) extends SExpression
case class SInteger(sint:Integer) extends SExpression
case class SFloat(sfloat:Double) extends SExpression
case class SList(sop:String,slist:List [SExpression]) extends SExpression
then a matching static object is created for each case class is created, this has apply and unapply methods, which means:
- You dont have to use the 'new' keyword to create an instance of the class.
- You can use 'match' to match constructor pattern.
In addition:
- All arguments get a val prefix.
- also toString is added