Created
July 22, 2012 13:28
-
-
Save masayuki038/3159683 to your computer and use it in GitHub Desktop.
A comparision of Non-Ordered.
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
package net.wrap_trap.scala.examples | |
import java.util.Comparator | |
object OrderedCompareTest2 { | |
def main(args : Array[String]) : Unit = { | |
System.out.println("called main") | |
// compile error when disabling nonOrderedClassToComparable Method. | |
// No implicit Ordering defined for | |
// net.wrap_trap.scala.examples.OrderedCompareTest2.NonOrderedClass. | |
System.out.println( | |
compareAB(new NonOrderedClass(4), new NonOrderedClass(3))) | |
} | |
class NonOrderedClass(val n: Int) {} | |
implicit def nonOrderedClassToComparable(from: NonOrderedClass): Comparable[NonOrderedClass] = { | |
new Comparable[NonOrderedClass] { | |
def compareTo(b: NonOrderedClass): Int = { | |
from.n - b.n | |
} | |
} | |
} | |
// View Bound from scala.math.LowPriorityOrderingImplicits | |
implicit def ordered[T <% Comparable[T]]: Ordering[T] = new Ordering[T] { | |
/* = implicit def ordered[T](implicit f: T => Comparable[T]): Ordering[T] = new Ordering[T] { */ | |
def compare(x: T, y: T): Int = { | |
x.compareTo(y) | |
} | |
} | |
// Context Bound | |
def compareAB[K:Ordering](a: K, b: K): Int = { | |
/* = def compareAB2[K](a: K, b: K)(implicit comp: Ordering[K]): Int = { */ | |
val comp = Ordering[K] | |
System.out.println("called compareAB comp:" + comp) | |
comp.compare(a, b); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment