Last active
March 4, 2019 09:26
-
-
Save samuelorji/2644f93cdfdfb3784358594d98717153 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
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