Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extension Methods in Java, Xtend and Scala
/* JAVA */
public class SampleExtensions {
public static String sort(String s) {
final char[] arr = s.toCharArray();
java.util.Arrays.sort(arr);
return String.valueOf(arr);
}
public static int checksum(String s) {
int i = 0;
for (char c : s.toCharArray()) { i += c; }
return i;
}
public static String toUpper(String s) {
return s.toUpperCase();
}
}
// bug? static imports from default package do not work for me!?
import static SampleExtensions.*;
public class Sample {
public static void main(String[] args) {
// explicitly use extensions
final String sorted = SampleExtensions.sort("Sort me!");
System.out.println(sorted);
final int summed = SampleExtensions.checksum("Sum me!");
System.out.println(summed);
final String string = SampleExtensions.toUpper("Upper me!");
System.out.println(string);
}
}
/* XTEND */
// extensions globally usable
import static extension SampleExtensions.*
class SampleExtensions {
def static sort(String it) {
toCharArray.sort.join
}
def static checksum(String it) {
toCharArray.fold(0)[a,b | a + b]
}
def static toUpper(String it) {
toUpperCase
}
}
class Sample {
def static void main(String[] args) {
val sorted = "Sort me!".sort
println(sorted)
val summed = "Sum me!".checksum
println(summed)
val string = "Upper me!".toUpper
println(string)
}
}
/* SCALA */
object SampleImplicits {
// mention class to be extended only once
implicit def stringWrapper(s: String) = new {
def sort() = s.sortWith(_ < _)
def checksum() = s.map(_.toInt).reduce(_ + _)
def toUpper() = s.toUpperCase
}
}
object Sample {
def main(args: Array[String]) = {
// use extensions where they are needed
import SampleImplicits._
val sorted = "Sort me!".sort
println(sorted)
val summed = "Sum me!".checksum
println(summed)
val string = "Upper me!".toUpper
println(string)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.