How do I create features that work with custom collections?

I'm having trouble declaring an empty collection - I can't use Nilit because it creates a subtype ...

def partiallyReduceString[S <: SeqLike[String, S]](reduction: String, seq: S): (String, S) =
  if (seq.nonEmpty)
    ...
  else
    (reduction, Nil)

I also tried CanBuildFrom, but I just get compile time errors ...

def partiallyReduceString ... (implicit bf: CanBuildFrom[S, String, S]): (String, S) =
  if (seq.nonEmpty)
    ...
  else
    (reduction, bf().result())

It is not possible to build a collection of type S with elements of type String based on a collection of type S.

+3
source share
1 answer

The problem is that the second element of your tuple must be of type S, which can be considered as a collection of SeqLike, but not vice versa. Therefore, even bf cannot help in this case.

, , , S List Array, . , S .

import scala.collection.SeqLike
implicit val emptyList = () => List()
implicit val emptyArray[T] = () => Array[T]()
def partiallyReduceString[S <: SeqLike[String, S]](reduction: String, seq: S)(implicit empty: () => S): (String, S) = {
  if (seq.nonEmpty)
    ???
  else
    (reduction, empty())
  }
+2

All Articles