Skip to content

Instantly share code, notes, and snippets.

// 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 / 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
@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 / 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 / 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 / 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 / BowlingKataRunner.scala
Created March 23, 2011 16:35
Sample solution to standard bowling kata (http://codingdojo.org/cgi-bin/wiki.pl?KataBowling) using Scala pattern matching and extractors
// Idiomatic solution using extrators
// Extractors allow us to bind parameters to an object and are usable in pattern matches to see if a pattern can apply to the params submitted.
// Note this is simialr to case classes, but works against an Object (which are like 'static' classes in Java). Also it incurs some performance penalties
// as opposed to using case classes
class BowlingForExtractors() {
def score(bowls:List[Int]) = scoreFrames(bowls).slice(0,10).sum // take the first 10 elements from the List and sum them..any additional elements are the result of additional strikes
def scoreFrames(bowls:List[Int]) : List[Int] = bowls match {
case Nil => List(0)
@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 / 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 / XmlPatternMatchin.scala
Created March 23, 2011 11:34
Simple example of XML pattern matching
import scala.xml._
val someXML = <a><b name="nameB1">valueB1</b><b name="nameB2">valueB2</b></a>
someXML match {
case <a>{b @ _* }</a> => for(theB <- b) println("MANUAL PATTERN MATCHING: " + theB \ "@name")
}
for(theB <- (someXML \\ "b")) println("BUILT IN XML SUPPORT: " + theB \ "@name")