Scala match both String and Array -


i trying call method foldleft on string/array object. like:

def dosth(obj: any): int = {   obj match {     case t: traversableonce[any] => t.foldleft(0)((rs: int, i: any) => ...)     case other => ...   } } 

but when call dosth("abc"), matches case other. want case t: traversableonce[any].

is there anyway this?

string not sub type of traversableonce. that's why not match traversableonce.

although string can implicitly convert stringops sub type of traversableonce. check predef.augmentstring

you can this. in case scala compiler implicitly convert string stringops. print out class scala.collection.immutable.stringops if pass in "hello"

def dosth(obj: traversableonce[any]): int = {     println(obj.getclass())     obj.foldleft(0)((rs: int, i: any) => ...) } 

and in following code. print out class java.lang.string if pass in "hello". means there no implicit conversion.

def dosth(obj: any): int = {   obj match {     case t: traversableonce[any] => t.foldleft(0)((rs: int, i: any) => ...)     case other =>        println(other.getclass)   } } 

Comments

Popular posts from this blog

c# SetCompatibleTextRenderingDefault must be called before the first -

c++ - Fill runtime data at compile time with templates -

C#.NET Oracle.ManagedDataAccess ConfigSchema.xsd -