Java vs Groovy vs Scala: A simple example

http://i-proving.ca/space/Mike+Wilkes/blog/2011-01-13_1

// Java version
List myList = new ArrayList();
myList.add("some value")
//Scala version
// Note: Scala uses [] rather than <> for generics. 
// < and > are valid in Scala method names, so can't be used in definitions.
val myList = new ArrayList[String]
myList.add("some value")
myList add "some other value"

// of course to make it truly Scala, it would become:
val myList = List("some value", "some other value")
// Java
  public void testMethod(IOutputable someObject) {
    someObject.output();
  }

 

// Groovy
  def testMethod(someObject) {
     someObject.output() // may throw a MissingMethod exception at runtime, so make sure you test
  }
//Scala
  def testMethod(someObject:{def output()}) = {
    someObject.output()
  }
//Java - what we're used to seeing
public String buildEpochKey(String... keys) {
  StringBuilder s = new StringBuilder("elem")
  for(String key:keys) {
    if(key != null) {
      s.append(".")
      s.append(key)
    }
  }
  return s.toString().toLowerCase()
}
//Groovy - still fairly straight forward to see what's happening. 
// NOTE: .with {} means that any method calls in the curly-braces will be called on
// the object before the .with. 
// i.e. addAll, retainAll and join will be called on keys2
def buildEpochKey(String... keys) {
  def keys2 = ["elem"]
  keys2.with {
    addAll(keys)
    retainAll{it != null}
    join(".").toLowerCase()
  }
}

 

//Scala 
// - in the method definition, keys is the variable. 
// String* is like Java's String...
// the : after the parenthesis with a type defines the method return type (i.e. String in this case)
def buildEpochKey(keys: String*): String = {
  ("elem" +: keys) filter(_ != null) mkString(".") toLowerCase
}

 

 

你可能感兴趣的:(java,scala,groovy)