Skip to content

Instantly share code, notes, and snippets.

@kings13y
kings13y / ExampleOfOptionClass.scala
Created March 23, 2011 15:54
Simple example of using an option class with method chaining (fluent builder) and sealed classes
sealed abstract class BetType
case object BackBet extends BetType
case object LayBet extends BetType
case class Bet(amount: Int, betType:Option[BetType])
val reservations = List(Bet(100, Option(BackBet)), Bet(200, None))
for(exposure <- reservations) println("Amount exposed: " + exposure.amount + " - type: " + exposure.betType.getOrElse("Reservation") + ".... sample method chaining " + exposure.betType.toString.reverse)
@kings13y
kings13y / SampleExtractorInjector.scala
Created March 23, 2011 16:27
Sample use of an Extractor and Injector in Scala
// Assuming we have a Name class, that accepts a firstname and lastname in its' Constructor
case class Name(firstname: String, lastname: String) { override def toString() = { firstname + "-" + lastname } }
// We could create an extractor for this that could (effectively) provide overloads for the Constructor
object Namer {
// optional injection method
def apply(x: String, y: String, z: Int) = Name(x,y)
// mandatory extraction method - take the dash delim string and return Some pair of names or None
def unapply(dashDelimName: String) = {
@kings13y
kings13y / typeInference.scala
Created June 14, 2011 22:09
Example of type inference in Scala
val a = 1 // this type gets inferred to be of type Int
val b = "b" // this type in inferred to be a String
val c = 2.0 // this type is inferred to be a Double
case class SomeThing
class SomeOtherThing
val d = SomeThing // this type is instantiated as SomeThing. Not no need for the 'new' keyword as this is a case class
val e = new SomeOtherThing // This type requires the new keyword as no factory method is created for non case classes
@kings13y
kings13y / StructuralTypeSample.scala
Created June 15, 2011 23:14
Static Duck Typing
class Duck {
def squawk = println("Quack")
def waddle = println("Duck walk")
}
class Pengiun {
def squawk = println("Squeek")
def waddle = println("Penguin walk")
}
class Person { }
@kings13y
kings13y / TypeTypes.scala
Created June 15, 2011 21:12
abstract types example
import scala.collection.GenSeq
trait SimpleListTypeContainer {
type Simple // declare an abstract type with the label Simple
type SimpleList <: GenSeq[Simple] // Constrain the Simple List abstract type based on the previously defined abstract type
}
@kings13y
kings13y / SelfRefType.scala
Created June 15, 2011 22:56
Self reference types
trait DB { def startDB: Unit } // defines an abstract start for a DB component
trait MT { def startMT: Unit } // defines an abstract start for an MT component
trait Oracle extends DB { def startDB = println("Starting Oracle") } // Some actual concrete instances.. dummied for example
trait Service extends MT { def startMT = println("Starting Service") }
trait App {
self: DB with MT => // declare that self for App refers to a DB with MT, so that we have access to the startXX ops
startDB
@kings13y
kings13y / PathDepTypeSample.scala
Created June 16, 2011 09:28
Path Dependent types example
// First a simple example of Tuple creation
val myTuple2 = ("A", 1)
val myTuple3 = ("B", 2, true) // creates a Tuple3 of String, Int, Boolean
// Not on to the path dep types stuff
trait BaseTrait {
type T
val baseA : T
// Taken from the excellent tutorial here:
// http://programming-scala.labs.oreilly.com/ch12.html#VarianceUnderInheritance
// Note this sample leverages the Function1 trait: Function1[-T, +R]
// WON'T COMPILE
class CSuper { def msuper = println("CSuper") }
class C extends CSuper { def m = println("C") }
class CSub extends C { def msub = println("CSub") }
@kings13y
kings13y / PrintFormatter.scala
Created June 16, 2011 21:38
Generalized type constraints example
case class PrintFormatter[T](item : T) {
def formatString(implicit evidence: T =:= String) = { // Will only work for String PrintFormatters
println("STRING specialised printformatting...")
}
def formatPrimitive(implicit evidence: T <:< AnyVal) = { // Will only work for Primitive PrintFormatters
println("WRAPPED PRIMITIVE specialised printformatting...")
}
}
val stringPrintFormatter = PrintFormatter("String to format...")
@kings13y
kings13y / ReifiedManifest.scala
Created June 16, 2011 22:45
Reification via a Manifest example
class ReifiedManifest[T <: Any : Manifest](value: T) {
val m = manifest[T] // So at this point we have the manifest for the Parameterized type
// At which point we could either do an if() expression on what type is contained in our manifest
if (m equals manifest[String]) {
println("The manifest contains a String")
} else if (m <:< manifest[AnyVal]) { // A subtype check using the <:< operation on the Manifest trait
println("The manifest contains a subtype of AnyVal")
} else if (m <:< manifest[AnyRef]) {