Last active
March 4, 2019 14:58
-
-
Save fancellu/db4ab6fa37c7ff13cd63caa03f462d82 to your computer and use it in GitHub Desktop.
Little Typeclass example
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
TwoPart(one,two) | |
ThreePart(one,two,three) |
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
case class Row(rowstring: String) | |
trait RowParse[A]{ | |
def parse(row:Row):A | |
} | |
case class TwoPart(v1: String, v2: String) | |
case class ThreePart(v1: String, v2: String, v3: String) | |
implicit object TwoPartParse extends RowParse[TwoPart]{ | |
def parse(row: Row)={ | |
val parts=row.rowstring.split(',') | |
TwoPart(parts(0),parts(1)) | |
} | |
} | |
implicit object ThreePartParse extends RowParse[ThreePart]{ | |
def parse(row: Row)={ | |
val parts=row.rowstring.split(',') | |
ThreePart(parts(0),parts(1),parts(2)) | |
} | |
} | |
object RowParse{ | |
def parse[A](row:Row)(implicit ev: RowParse[A]):A={ | |
ev.parse(row) | |
} | |
} | |
val row2=Row("one,two") | |
println(RowParse.parse[TwoPart](row2)) | |
val row3=Row("one,two,three") | |
println(RowParse.parse[ThreePart](row3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment