Saturday, 31 August 2013

Structural-type casting does not work with String?

Structural-type casting does not work with String?

Given these definitions:
type HasMkString = { def mkString(sep:String):String }
val name = "John"
val names = List("Peter", "Gabriel")
And given these facts:
name.mkString("-") // => "J-o-h-n"
name.isInstanceOf[HasMkString] // => true
names.isInstanceOf[HasMkString] // => true
While this works:
names.asInstanceOf[HasMkString].mkString("-")
// => Peter-Gabriel
This does not work:
name.asInstanceOf[HasMkString].mkString(", ")
java.lang.NoSuchMethodException: java.lang.String.mkString(java.lang.String)
at java.lang.Class.getMethod(Class.java:1624)
at .reflMethod$Method1(<console>:10)
at .<init>(<console>:10)
at .<clinit>(<console>:10)
at .<init>(<console>:7)
at .<clinit>(<console>)
at $print(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
Why is that? Is it because String is a Java class? Can I work around this
problem? Is this a bug/shortcoming in the Scala implementation?

No comments:

Post a Comment