Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
example of a reasonable Singleton
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);
public static <T extends Comparable<?>> Comparator<T> getInstance(){
return (Comparator<T>) instance;
private NaturalComparator(){}
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
import v6ak.util.NaturalComparator
import java.util.Comparator
import java.lang.Integer
def compareChars(a:Char, b:Char, cmp: Comparator[Char]){
println(, b))
val intCmp = NaturalComparator[Integer]
val strCmp = NaturalComparator[String]
val universalCmp = NaturalComparator
val universalCmp2 = NaturalComparator()
println( valueOf 1, Integer valueOf 2))
println("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("b", Integer valueOf 5)) // String would have to be able to compare itself with anything.
// println("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("a", "b"))
// println("a", "b"))
compareChars('r', 'r', NaturalComparator()) // The type of comparator is inferred. However, it is neccessary to add braaces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment