Last active
December 10, 2015 01:34
-
-
Save NIA/4358648 to your computer and use it in GitHub Desktop.
Demonstrates how implicit parameters can be scoped in Scala
This file contains hidden or 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
class Jedi(val name: String, val force: Double) { | |
override def toString = name + " with force " + force | |
} | |
def findMostPowerfulOf(jedies: Set[Jedi]) = { | |
implicit val jediOrdering = Ordering by { x:Jedi => x.force } | |
jedies.max | |
} | |
def findLastNameOf(jedies: Set[Jedi]) = { | |
implicit val jediOrdering = Ordering by { x:Jedi => x.name } | |
jedies.max | |
} | |
def findMaxOf(jedies: Set[Jedi], by: Symbol) = { | |
if (by == 'Force) { | |
implicit val jediOrdering = Ordering by { x:Jedi => x.force } | |
"Max force has " + jedies.max | |
} else { | |
implicit val jediOrdering = Ordering by { x:Jedi => x.name } | |
"Last name has " + jedies.max | |
} | |
} | |
val jedies = Set( new Jedi("Skywalker", 100), new Jedi("Obi-Wan", 200), new Jedi("Yoda", 5000), new Jedi("Zal", 80) ) | |
println( findMostPowerfulOf(jedies) ) // => Yoda with force 5000.0 | |
println( findLastNameOf(jedies) ) // => Zal with force 80.0 | |
println( findMaxOf(jedies, 'Force) ) // => Yoda with force 5000.0 | |
println( findMaxOf(jedies, 'Name) ) // => Zal with force 80.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment