Created
February 22, 2017 13:57
-
-
Save mvervuurt/b2b5a15bdb5cf5b13dbf013fa8dbbd41 to your computer and use it in GitHub Desktop.
Teaching basic scala concepts
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
/** Simple Base **/ | |
abstract class Animal { | |
def hasNose : Boolean | |
def hasLegs : Boolean | |
def numLegs : Int | |
} | |
/** Example Traits **/ | |
trait Mammal { | |
def isMammal : Unit = { | |
println("Mammal Class \n") | |
} | |
trait Tail { | |
def hasTail : Unit = { | |
println("Give me my tail \n") | |
} | |
} | |
trait Reptile { | |
def isReptile : Unit = { | |
println("Direct descendant from dinosaurs \n") | |
} | |
} | |
/** Example implementation **/ | |
class Dog extends Animal with Tail{ | |
override def hasNose : Boolean = { | |
true | |
} | |
override def hasLegs : Boolean = { | |
true | |
} | |
override def numLegs : Int = { | |
4 | |
} | |
} | |
val myDog = new Dog | |
myDog.hasLegs | |
myDog.hasNose | |
myDog.numLegs | |
myDog.hasTail | |
/** Scala Collections **/ | |
val myList = List(1,2,3,4,5,6,7,8,9,10) | |
/** Higher order functions **/ | |
def myAdd(x : Int) : Int = { | |
x + 1 | |
} | |
myList.map(x => myAdd(x)) | |
/** Case Classes **/ | |
trait Being | |
case class Person(name : String, Age : Int) extends Being | |
val p1 = Person("John", 32) | |
val p2 = Person("Maria", 28) | |
case class AlienFromMars(name : String, Age : Int) extends Being | |
val a1 = AlienFromMars("Joe", 1001) | |
val a2 = AlienFromMars("Kris", 3333) | |
case class UnknownBeing(name: String) extends Being | |
val u1 = UnknownBeing("What am I?") | |
/** Pattern Matching **/ | |
def AlienOrPerson(livingBeing : Being) : Unit = livingBeing match { | |
case Person("John", _) => println("This is John") | |
case Person(_ , _ ) => println("This is a person") | |
case AlienFromMars("Joe",_) => println ("This is Alien Joe from Mars") | |
case AlienFromMars(_,_) => println("This is an Alien from Mars") | |
case _ => println("This is an unknow being") | |
} | |
AlienOrPerson(p1) | |
AlienOrPerson(p2) | |
AlienOrPerson(a1) | |
AlienOrPerson(a2) | |
AlienOrPerson(u1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment