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?

1
  • Of course Array is not TraversableOnce either, it can only be converted to it, just like String. Commented Nov 8, 2016 at 17:28

1 Answer 1

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)
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

So in match/case, scala will not try to implicitly convert to StringOps?
You could; case t: String => { val x: TraversableOnce[Any] = t; doSth(x)}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.