Skip to content

Instantly share code, notes, and snippets.

@samuelorji
Last active March 4, 2019 09:26
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 samuelorji/2644f93cdfdfb3784358594d98717153 to your computer and use it in GitHub Desktop.
Save samuelorji/2644f93cdfdfb3784358594d98717153 to your computer and use it in GitHub Desktop.
implicit class ToParrot( p : Parrot){
def speakLikeHuman(implicit humanlike : HumanTendency[Parrot]) : String = {
humanlike.makeHumanLike(p)
}
}
//let us create our closed model object type Parrot
val parrot = Parrot("Casey", "prrrrr")
//closed object type Cat
val cat = Cat("Puss", "meow")
//now with the first method, the type class will work like this
//we call the method passing the parrot as a parameter like
// speakLikeHum
def speakLikeHuman(p :Parrot)(implicit humanTendency: HumanTendency[Parrot]) : String = { //#1
humanTendency.makeHumanLike(p)
}
//but with the second method,we can easily do this
parrot.speakLikeHuman //#2
println ( speakLikeHuman(parrot) ) // prints out ---------> I am Casey, the sound i make is prrrrr,and i can talk like a human :)
println( parrot.speakLikeHuman ) // prints out ---------> I am Casey, the sound i make is prrrrr,and i can talk like a human :)
//Now if we try this
println( cat.speakLikeHuman ) //error : value speakLikeHuman is not a member of Cat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment