Skip to content

Instantly share code, notes, and snippets.

@debasishg
Created September 11, 2010 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debasishg/575091 to your computer and use it in GitHub Desktop.
Save debasishg/575091 to your computer and use it in GitHub Desktop.
trait Read[T] {
def read(st: String): T
}
implicit object IntRead extends Read[Int] {
def read(s: String) = s.toInt
}
implicit object StringRead extends Read[String] {
def read(s: String) = s
}
// for generic list
implicit def ListRead[A](implicit r: Read[A]) =
new Read[List[A]] {
def read(s: String) = {
val es = s.split(" ").toList
es.map(r.read(_))
}
}
// for list of strings : read converts to upper case also
implicit def ListStringRead(implicit r: Read[String]) =
new Read[List[String]] {
def read(s: String) = {
val es = s.split(" ").toList
es.map(r.read(_).toUpperCase)
}
}
def foo[T : Read](s: String) = implicitly[Read[T]].read(s)
foo[List[Int]]("1 2 3 4") // List(1, 2, 3, 4)
foo[List[String]]("a b c d") // List("A", "B", "C", "D")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment