Skip to content

Instantly share code, notes, and snippets.

Kingsley Davies kings13y

Block or report user

Report or block kings13y

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
View VarianceAnnotationsExample.scala
// 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 Jun 16, 2011
Path Dependent types example
View PathDepTypeSample.scala
// 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
View StructuralTypeSample.scala
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 Jun 15, 2011
Self reference types
View SelfRefType.scala
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 Jun 15, 2011
abstract types example
View TypeTypes.scala
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 Jun 14, 2011
Example of type inference in Scala
View typeInference.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 Mar 23, 2011
Sample solution to standard bowling kata (http://codingdojo.org/cgi-bin/wiki.pl?KataBowling) using Scala pattern matching and extractors
View BowlingKataRunner.scala
// 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 Mar 23, 2011
Sample use of an Extractor and Injector in Scala
View SampleExtractorInjector.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 Mar 23, 2011
Simple example of using an option class with method chaining (fluent builder) and sealed classes
View ExampleOfOptionClass.scala
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 Mar 23, 2011
Simple example of XML pattern matching
View XmlPatternMatchin.scala
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")
You can’t perform that action at this time.