This line will fail:
"Hello".asInstanceOf[Iterable[Char]]
But I can pass an instance of a String to a method like this:
def someMethod(input: Iterable[Char]): Unit = { ... }
someMethod("Hello")
Why?
A java list can be converted to an iterator in Scala by utilizing toIterator method of Java in Scala. Here, we need to import Scala's JavaConversions object in order to make this conversions work else an error will occur.
String does not extend Iterable[Char]. That explains why casting fails.
However, the Scala Predef defines an implicit conversion from String to WrappedString, and WrappedString does extend Iterable[Char]. That's why your second example works. The compiler adds the conversion, so the compiled code looks more like this:
someMethod(wrapString("Hello"))
If you're wondering why it was done this way, it's because String is actually java.lang.String from the Java standard library (for Java compatibility reasons), so WrappedString was created as an adapter to make String fit within the Scala collections library, and an implicit conversion was added to make this nearly seamless.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With