Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce Strict Collections

Tags:

scala

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])
like image 287
Jack Koenig Avatar asked Apr 24 '26 00:04

Jack Koenig


1 Answers

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
like image 127
Roberto Bonvallet Avatar answered Apr 27 '26 04:04

Roberto Bonvallet