public
Last active

example of a reasonable Singleton

  • Download Gist
NaturalComparator.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
package v6ak.util;
 
import java.util.Comparator;
 
public final class NaturalComparator {
 
private static final Comparator<? extends Comparable<?>> instance = new Comparator<Comparable<Object>>(){
public int compare(Comparable<Object> o1, Comparable<Object> o2) {
if( o1==null || o2==null ){
throw new NullPointerException("Comparing null values is not supported!");
}
return o1.compareTo(o2);
}
};
@SuppressWarnings("unchecked")
public static <T extends Comparable<?>> Comparator<T> getInstance(){
return (Comparator<T>) instance;
}
private NaturalComparator(){}
}
NaturalComparator.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package v6ak.util
 
import java.util.Comparator
 
object NaturalComparator extends Comparator[Comparable[Any]]{
 
def apply[T]() = asInstanceOf[Comparator[T]]
 
override def compare(o1:Comparable[Any], o2:Comparable[Any]) = {
if( o1 == null || o2 == null ){
throw new NullPointerException("Comparing null values is not supported!")
}
o1 compareTo o2
}
 
}
scala-NaturalComparator-example.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
import v6ak.util.NaturalComparator
import java.util.Comparator
import java.lang.Integer
 
def compareChars(a:Char, b:Char, cmp: Comparator[Char]){
println(cmp.compare(a, b))
}
 
val intCmp = NaturalComparator[Integer]
val strCmp = NaturalComparator[String]
val universalCmp = NaturalComparator
val universalCmp2 = NaturalComparator()
 
println(intCmp.compare(Integer valueOf 1, Integer valueOf 2))
println(strCmp.compare("b", "a"))
 
println(intCmp eq strCmp) // intCmp and strCmp are the same, but they are casted to a different type
 
// Following two commented commands can't be compiled, of course. It does not make sense.
// println(universalCmp.compare("b", Integer valueOf 5)) // String would have to be able to compare itself with anything.
// println(universalCmp2.compare("b", Integer valueOf 5)) // There is not enough type info provided, so it can't be used.
 
// Following two commented commands can't be compiled. They make sense, but type information is too restrictive.
// println(universalCmp2.compare("a", "b"))
// println(universalCmp.compare("a", "b"))
 
compareChars('r', 'r', NaturalComparator()) // The type of comparator is inferred. However, it is neccessary to add braaces.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.