Boy.scala
class Boy(val name: String, val faceValue: Int) extends Comparable[Boy]{ override def compareTo(o: Boy): Int = { this.faceValue - o.faceValue }}
Girl.scala
class Girl(val name: String, val faceValue: Int, val size: Int) {}
MissLeft.scala
//class MissLeft[T <% Ordered[T]] {//// def choose(first: T, second: T) : T = {// if (first > second) first else second// }////}class MissLeft[T : Ordering] { def choose(first: T, second: T): T = { val ord = implicitly[Ordering[T]] if(ord.gt(first, second)) first else second }}object MissLeft { def main(args: Array[String]) { import MyPreDef.girlOrdering val ml = new MissLeft[Girl] val g1 = new Girl("hatanao", 98, 28) val g2 = new Girl("sora", 95, 33) val g = ml.choose(g1, g2) println(g.name) }}
MissRight.scala
class MissRight[T] { def choose(first: T, second: T)(implicit ord : T => Ordered[T]): T = { if(first > second) first else second } def select(first: T, second: T)(implicit ord : Ordering[T]): T ={ if(ord.gt(first, second)) first else second } def random(first: T, second: T)(implicit ord : Ordering[T]): T ={ import Ordered.orderingToOrdered if(first > second) first else second }}object MissRight { def main(args: Array[String]) { val mr = new MissRight[Girl] val g1 = new Girl("hatanao", 98, 28) val g2 = new Girl("sora", 95, 33) import MyPreDef.girlOrdering //val g = mr.choose(g1, g2) val g = mr.select(g1, g2) println(g.name) }}
MyPreDef.scala
object MyPreDef { implicit def girlToOrdered(girl: Girl) = new Ordered[Girl]{ override def compare(that: Girl): Int = { if(girl.faceValue == that.faceValue) { girl.size - that.size } else { girl.faceValue - that.faceValue } } } implicit object girlOrdering extends Ordering[Girl] { override def compare(x: Girl, y: Girl): Int = { if(x.faceValue == y.faceValue) { x.size - y.size } else { x.faceValue - y.faceValue } } }}
MrRight.scala
class MrRight[T] { def choose[T <: Comparable[T]](first: T, second: T): T = { if(first.compareTo(second) > 0) first else second }}object MrRight { def main(args: Array[String]) { val mr = new MrRight[Boy] val b1 = new Boy("zhangsan", 99) val b2 = new Boy("lisi", 100) val b = mr.choose(b1, b2) println(b.name) }}