Created
March 23, 2011 16:27
-
-
Save kings13y/883389 to your computer and use it in GitHub Desktop.
Sample use of an Extractor and Injector in Scala
This file contains hidden or 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
// 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) = { | |
var elems = dashDelimName.split("-") | |
if(elems.length == 2) Some(elems(0), elems(1)) else None | |
} | |
} | |
var someName = Namer("bob", "wood", 22) | |
Namer.unapply(someName.toString) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment