Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Seq - accept only elements of the same subtype

Assuming I have a type hierarchy like the following:

trait Color
case class Red(r: String) extends Color
case class Green(g: String) extends Color

Is it possible to create a method that accepts a Seq[Color] that contains elements of either all Red, or either all Green, but not both?

For example in the following code:

def process[T](colors: Seq[T]) = colors.size

process(Seq(Red("a"), Green("g")))

what should [T] be so that the above does not type-check?

Edit

The original problem is the following: I am trying to devise a JSON API for nested queries. I have come up with the following design:

trait QueryUnit
case class SimpleQuery(query: String, metadata: Metadata)
case class ComplexQuery(Map[String, Seq[SimpleQuery])

case class API(
  query: Map[String, Seq[QueryUnit]]
)

The elements of the Map will be conjuctions (ANDs), while the elements of the Seq will be disjunctions(ORs). I do not want to mix Simple with ComplexQueries, and I am planning to pattern match on the Seq[QueryUnit].

like image 709
spyk Avatar asked Oct 17 '22 02:10

spyk


1 Answers

Try this (partially based on this blog post from Miles Sabin):

// Your domain
trait QueryUnit
case class SimpleQuery(query: String, metadata: AnyRef) extends QueryUnit
case class ComplexQuery(map: Map[String, Seq[SimpleQuery]]) extends QueryUnit
// End of your domain

// Something which has type parameter, so we can add QueryUnit, ...
trait WrongArg[T]

// Create ambiguous implicits for QueryUnit
implicit def v0: WrongArg[QueryUnit] = ???
implicit def v2: WrongArg[QueryUnit] = ???

// And valid values for the concrete subclasses
implicit val simpleQWrongArg: WrongArg[SimpleQuery] = new WrongArg[SimpleQuery] {}
implicit val complexQWrongArg: WrongArg[ComplexQuery] = new WrongArg[ComplexQuery] {}

case class API[QU <: QueryUnit](
                query: Map[String, Seq[QU]]
     // Require an evidence that we are getting the correct type
                               )(implicit w: WrongArg[QU]) {
}

API/*[SimpleQuery]*/(Map("" -> Seq(SimpleQuery("", ""))))

API/*[ComplexQuery]*/(Map("" -> Seq(ComplexQuery(Map.empty))))

// Fails to compile because of ambiguous implicits
//API(Map("s" -> Seq(SimpleQuery("", "")), "c" -> Seq(ComplexQuery(Map.empty))))

It is not ideal (wrong names, no @implicitNotFound annotation).

The basic idea is that we create ambiguous implicits for the base class, but not for the subclasses. Because of the implicit resolution rules this will compile only for the subclasses, but not for the base class.

A cleaned up version:

@annotation.implicitNotFound("Base QueryUnit is not supported, you cannot mix SimpleQuery and ComplexQuery")
trait Handler[T] extends (T => Unit)

object API {
  implicit def baseQueryUnitIsNotSupported0: Handler[QueryUnit] = ???

  implicit def baseQueryUnitIsNotSupported1: Handler[QueryUnit] = ???

  implicit val simpleQWrongArg: Handler[SimpleQuery] = new Handler[SimpleQuery] {
    override def apply(s: SimpleQuery): Unit = {}
  }
  implicit val complexQWrongArg: Handler[ComplexQuery] = new Handler[ComplexQuery] {
    override def apply(s: ComplexQuery): Unit = {}
  }
}

case class API[QU <: QueryUnit](query: Map[String, Seq[QU]])(
  implicit handler: Handler[QU]) {
  // Do something with handler for each input
}

// Usage

import API._

import scala.annotation.implicitNotFound
API/*[SimpleQuery]*/(Map("" -> Seq(SimpleQuery("", ""))))

API/*[ComplexQuery]*/(Map("" -> Seq(ComplexQuery(Map.empty))))

// Error:(56, 71) Base QueryUnit is not supported, you cannot mix SimpleQuery and ComplexQuery
//API(Map("s" -> Seq(SimpleQuery("", "")), "c" -> Seq(ComplexQuery(Map.empty))))

Alternatively with type bounds and implicitly:

case class API[QU <: QueryUnit: Handler](query: Map[String, Seq[QU]]) {
  def doSomething: Unit = for {(_, vs) <- query
       v <- vs} {
    val handler: Handler[QU] = implicitly[Handler[QU]]
    handler(v)
  }
}
like image 123
Gábor Bakos Avatar answered Nov 15 '22 08:11

Gábor Bakos