Last active
December 19, 2015 01:19
-
-
Save rumblesan/5875534 to your computer and use it in GitHub Desktop.
So typeclasses in scala are pretty cool...
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 UserInfo(name: String, email: String) | |
case class PaidUser(id: Long, name: String, email: String, payments: Double) | |
object PaidUser { | |
class PaidUserExtended(user: PaidUser) { | |
def userInfo: UserInfo = UserInfo(user.name, user.email) | |
} | |
implicit def PaidUser2Extended(user: PaidUser) = new PaidUserExtended(user) | |
} | |
case class BasicUser(id: Long, name: String, email: String) | |
object BasicUser { | |
class BasicUserExtended(user: BasicUser) { | |
def userInfo: UserInfo = UserInfo(user.name, user.email) | |
} | |
implicit def BasicUser2Extended(user: BasicUser) = new BasicUserExtended(user) | |
} | |
val basic = BasicUser(1, "foo bar", "[email protected]") | |
val paid = PaidUser(1, "baz bim", "[email protected]", 55.4) | |
println(basic.userInfo) | |
// UserInfo(foo bar,[email protected]) | |
println(paid.userInfo) | |
// UserInfo(baz bim,[email protected]) |
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 BasicUser(id: Long, name: String, email: String) | |
case class PaidUser(id: Long, name: String, email: String, payments: Double) | |
case class UserInfo(name: String, email: String) | |
object UserInfoMethods { | |
trait UserInfoLike[T] { | |
def getUserInfo(user: T): UserInfo | |
} | |
object UserInfoLike { | |
// The implicits here can be vals or objects, depending on what you prefer | |
implicit val UserInfoLikeBasic = new UserInfoLike[BasicUser] { | |
def getUserInfo(user: BasicUser): UserInfo = UserInfo(user.name, user.email) | |
} | |
implicit object UserInfoLikePaid extends UserInfoLike[PaidUser] { | |
def getUserInfo(user: PaidUser): UserInfo = UserInfo(user.name, user.email) | |
} | |
} | |
def userInfo[T](user: T)(implicit tc: UserInfoLike[T]): UserInfo = tc.getUserInfo(user) | |
} | |
val basic = BasicUser(1, "foo bar", "[email protected]") | |
val paid = PaidUser(1, "baz bim", "[email protected]", 55.4) | |
println(UserInfoMethods.userInfo(basic)) | |
// UserInfo(foo bar,[email protected]) | |
println(UserInfoMethods.userInfo(paid)) | |
// UserInfo(baz bim,[email protected]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment