Question

I'm playing around with folds in Scala and, for whatever reason, ended up trying to test whether a String contains only unique characters by doing the following:

str
  .fold(""){ (x, y) => if (!(x contains y)) x + y else x }
  .size == str.size

This results in the error

error: type mismatch;
found: Any
required: String

apparently pointing to the value of y.

Can anyone provide insight into this?

I wouldn't have expected this behavior, and the closest answer I could find with respect to this was "Scala assumes wrong type when using foldLeft," which is similar, but doesn't quite clarify things.

Était-ce utile?

La solution

You should use foldLeft instead of fold:

str
  .foldLeft(""){ (x, y) => if (!(x contains y)) x + y else x }
  .size == str.size

the signature for fold is:

fold[A1 >: Char](z: A1)(op: (A1, A1) ⇒ A1): A1 

So fold expects the element type to be a lower bound on the accumulator type. The element type is Char in the case of String, so the possible types for A1 are Char, AnyVal and Any. You pass a String so Any is the only common type, which means x and y have type Any, which does not have a contains method.

You need to the accumulator type to be different from the element type so you need to use foldLeft.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top