Skip to content

Instantly share code, notes, and snippets.

@hossshy
Created January 14, 2016 06:05
Show Gist options
  • Save hossshy/390171f45e5422eac9fa to your computer and use it in GitHub Desktop.
Save hossshy/390171f45e5422eac9fa to your computer and use it in GitHub Desktop.
package chapter3.inheritance
/**
* Created by hoshi on 1/14/16.
*/
class Vehicle(speed: Int) {
val mph: Int = speed
def race() = println("Racing MPH:" + speed)
}
/*
* Method overriding requires the "override" keyword
* Only the primary constructor can pass parameters to the base constructor
*/
class Car(speed: Int) extends Vehicle(speed) {
override val mph: Int = speed
override def race() = println("Racing Car MPH:" + mph)
}
class Bike(speed: Int) extends Vehicle(speed) {
override val mph: Int = speed
override def race() = println("Racing Bike MPH:" + mph)
}
trait flying {
def fly() = println("flying")
}
trait gliding {
def gliding() = println("gliding")
}
class Batmobile(speed: Int) extends Vehicle(speed) with flying with gliding {
override def race() = println("Racing Batmobile MPH:" + mph)
override def fly() = println("Flying Batmobile")
}
object VehicleMain extends App {
val v1 = new Car(200)
v1.race()
val v2 = new Bike(100)
v2.race()
val v3 = new Batmobile(300)
v3.race()
v3.fly()
v3.gliding()
// Using maxBy
val vList = List(v1, v2, v3)
val fastest = vList.maxBy(_.mph)
fastest.race()
}
----
package chapter3.inheritance
/**
* Created by hoshi on 1/14/16.
* case class provides toString, hashCode, and equals
*/
case class Stuff(name: String, age: Int)
object CaseClassMain {
def main(args: Array[String]) {
val s = new Stuff("David", 45)
println(s)
println(s == Stuff("David", 45))
println(s == Stuff("David", 43))
println(s.name)
println(s.age)
}
}
----
package chapter3.inheritance
/**
* Created by hoshi on 1/14/16.
*/
class ValueClass(val i: Int) extends AnyVal {
def twice() = i * 2
}
object ValueClassMain extends App {
def with42(in: Int => Int) = in(42)
val v = new ValueClass(9)
println(v.twice())
//etc (legal in Scala)
println(1.hashCode())
println(2.toString)
// give a unction
println(with42(33 +))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment