Minh Thai Minh Thai - 1 month ago 9
Scala Question

Scala match both String and Array

I am trying to call the method foldLeft on String/Array object. Something like:

def doSth(obj: Any): Int = {
obj match {
case t: TraversableOnce[Any] => t.foldLeft(0)((rs: Int, i: Any) => ...)
case other => ...
}
}


but when I call
doSth("abc")
, it matches
case other
. What I want is
case t: TraversableOnce[Any]
.

Is there anyway to do this?

Answer

String is not a sub type of TraversableOnce. That's why It will not match TraversableOnce.

Although String can be implicitly convert to StringOps which is a sub type of TraversableOnce. check Predef.augmentString

You can do like this. In this case scala compiler will implicitly convert String to StringOps. It will print out class scala.collection.immutable.StringOps if we pass in a "hello"

def doSth(obj: TraversableOnce[Any]): Int = {
    println(obj.getClass())
    obj.foldLeft(0)((rs: Int, i: Any) => ...)
}

And in the following code. It will print out class java.lang.String if we pass in a "hello". Which means there is 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)
  }
}