Skip to content

Instantly share code, notes, and snippets.

@itang
Created January 15, 2012 07:55
Show Gist options
  • Save itang/1614986 to your computer and use it in GitHub Desktop.
Save itang/1614986 to your computer and use it in GitHub Desktop.
Scala Array Java Interop
package t;
public class Strings {
public static String join(Object[] args) {
if (args == null || args.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
sb.append(args[0]);
for (int i = 1, len = args.length; i < len; i++) {
sb.append(",").append(args[i]);
}
return sb.toString();
}
// test
public static void main(String[] args) {
join(new String[] { "Hello", "world" });
}
}
package t
object Test extends App {
import Strings.join
// val arr : Array[Any] = Array("a")
//join(arr)
val arr1: Array[AnyRef] = Array("a")
join(arr1)
//val arr2 = Array("a")
//join(arr2)
val arr3 = Array("a") // arr3: Array[String]
join(arr3.asInstanceOf[Array[AnyRef]]) //
assert(join(Array("hello", "world")) == "hello,world")
//assert(join(Array(1, 2)) == "1,2")
//assert(join(Array(1, 2).asInstanceOf[Array[AnyRef]]) == "1,2")
assert(join(Array(1, 2).map(_.toString).toArray) == "1,2")
assert(join(List[java.lang.Integer](1, 2).toArray) == "1,2")
def test(arr: Array[Any]) = {
//Strings.join(arr)
Strings.join(arr.asInstanceOf[Array[AnyRef]])
}
println(test(Array(1, 2, 3)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment