Created
February 25, 2014 08:24
-
-
Save tbje/9204998 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Trond { | |
val age = 25 // value - immutable variable - final in java | |
def sayHi = println(s"My name is Trond and I'm $age years old!") // definition - method | |
} | |
// Trond.age = 27 does not compile as age is immutable (val) | |
Trond.sayHi | |
object Eli { // singleton object - only one of these in the JVM | |
var age = 22 // variable (mutable) | |
def sayHi = println(s"My name is Eli and I'm $age years old!") | |
} | |
Eli.age = 27 // compiles as age is mutable (var) | |
class Person(val name: String, val age: Int) { // adding the val will promote the class parameter to a field | |
def sayHi = println(s"My name is $name and I'm $age years old!") // string interpolation - use $ or ${} to access variables | |
} | |
val elisabeth = new Person("Elisabeth", 22) // the type is infered by the compiler | |
val trond : Person = new Person("Trond", 25) // we can also explicitly specify the type | |
// Let's make everyone say hi | |
def introduceAll(persons: List[Person]) = { | |
for (p <- persons) p.sayHi | |
} | |
introduceAll(List(elisabeth, trond)) | |
// a tiny bit of inheritance | |
class Organiser(name: String, age: Int, task: String) extends Person(name, age) { | |
override def sayHi = println(s"My name is $name ($age) and today I will $task.") // we specialise the sayHi for the Organiser | |
} | |
introduceAll(List(elisabeth, trond, new Organiser("Antoine", 24, "present Spray"))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment