Created
September 11, 2010 10:57
-
-
Save debasishg/575091 to your computer and use it in GitHub Desktop.
This file contains 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
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