Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I cast an instance of a String to Iterable[Char] in Scala

Tags:

scala

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?

like image 873
user3640028 Avatar asked Aug 23 '18 07:08

user3640028


People also ask

How to convert list to Iterable in Scala?

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.


1 Answers

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.

like image 141
Brian McCutchon Avatar answered Nov 14 '22 21:11

Brian McCutchon