Last active
August 26, 2016 01:57
-
-
Save mpkocher/e8ac8439aecd8b803202be1c746f34a2 to your computer and use it in GitHub Desktop.
Scala Implicit Example
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
object Example { | |
trait DataSet { | |
def name: String | |
} | |
case class SubreadSet(name: String) extends DataSet | |
case class AlignSet(name: String) extends DataSet | |
case class RefSet(name: String) extends DataSet | |
trait Loader[T <: DataSet] { | |
def load(ds: String): T | |
} | |
implicit object LoadSubreadSet extends Loader[SubreadSet] { | |
def load(ds: String) = SubreadSet(ds) | |
} | |
implicit object LoadAlignSet extends Loader[AlignSet] { | |
def load(ds: String) = AlignSet(ds) | |
} | |
implicit object LoadRefSet extends Loader[RefSet] { | |
def load(ds: String) = RefSet(ds) | |
} | |
def loader[T <: DataSet](ds: String)(implicit loader: Loader[T]) = loader.load(ds) | |
trait Validator[T <: DataSet] { | |
def validate(ds: T): Boolean | |
} | |
implicit object ValidateSubreadSet extends Validator[SubreadSet] { | |
override def validate(subreadSet: SubreadSet): Boolean = true | |
} | |
implicit object ValidateReferenceSet extends Validator[RefSet] { | |
override def validate(refSet: RefSet) = false | |
} | |
implicit object ValidateAlignSet extends Validator[AlignSet] { | |
override def validate(ds: AlignSet): Boolean = true | |
} | |
def validator[T <: DataSet](ds: T)(implicit vx: Validator[T]) = vx.validate(ds) | |
def runDemo = { | |
val sx = "SubreadSet-1234" | |
val s1 = loader[SubreadSet](sx) | |
println(s"SubreadSet loaded $s1 is valid? ${validator(s1)}") | |
val s = SubreadSet("SubreadSet") | |
val a = AlignSet("AlignSet") | |
val r = RefSet("RefSet") | |
println(s"${s} is valid? ${validator(s)}") | |
println(s"${a} is valid? ${validator(a)}") | |
println(s"${r} is valid? ${validator(r)}") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment