Created
January 15, 2012 07:55
-
-
Save itang/1614986 to your computer and use it in GitHub Desktop.
Scala Array Java Interop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" }); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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