Posts Tagged ‘Scala’

Appreciating Scala – Java 2 scala example

August 24, 2013

One reason I appreciate the scala programming language is that it enables me to convert  a real life example of Java 7 code like this:

public static <T extends Annotation> String[] getMethodsWithAnnotation
  (Class<?> commandClass, Class<T> annotationClass)
  {
      ArrayList<String> result = new ArrayList<>();
      Method[] methods = commandClass.getMethods();
      java.util.Arrays.sort(methods, new Comparator<Method>() {
        @Override
        public int compare(Method m1, Method m2) {
            return m1.getName().compareTo(m2.getName());
        }});
      
      for(Method method : methods)
      {
         if (method.getAnnotation(annotationClass)!=null)
             result.add(method.getName());
      }
      
      return result.toArray(new String[result.size()]);  
}

into concise Scala code like this:

def getMethodsWithAnnotation[T <: Annotation]
  (commandClass: Class[_], annotationClass: Class[T]): Array[String] = {
    commandClass.getMethods
      .filter(m=>m.getAnnotation(annotationClass)!= null)
        .sortBy(m => m.getName()).map(m=>m.getName())
}

🙂


Design a site like this with WordPress.com
Get started