0

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?

Minh Thai
  • 568
  • 6
  • 18

1 Answers1

4

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)
  }
}
Rockie Yang
  • 4,725
  • 31
  • 34