Is there an easy way using the Scala type-system and ideally no runtime overhead to enforce strict collections? I would love something like the below but perusing the Scala collections API I don't see any such hierarchy. I would prefer to not have to use a whitelist of strict collections but if that's the only way, I'll live with it.
case class Foo(xs: immutable.StrictSeq[Int])
Scala Seqs don't capture enough information to decide whether they are strict or not.
You can whitelist the sequences you'll accept like this:
import scala.language.higherKinds
// Tag for sequences that are strict.
sealed trait StrictSeq[T[_] <: Seq[_]]
object StrictSeq {
// Evidence for the compiler that lists and vectors are strict.
implicit object ListIsStrict extends StrictSeq[List]
implicit object VectorIsStrict extends StrictSeq[Vector]
}
// Restrict S to be a sequence and to have been tagged as strict.
case class Foo[S[_] <: Seq[_] : StrictSeq](xs: S[Int])
Foo(List(1, 2, 3)) // OK
Foo(Vector(1, 2, 3)) // OK
Foo(Stream(1, 2, 3)) // Compile-time error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With