5

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].

spyk
  • 878
  • 1
  • 9
  • 26
  • 1
    Sounds like the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. Could you elaborate a bit on the problem? – Yuval Itzchakov Dec 02 '17 at 14:53
  • 1
    Sure, fair enough :) I will update with more info on my original issue. – spyk Dec 02 '17 at 15:02
  • Updated with original problem – spyk Dec 02 '17 at 15:13
  • 2
    Have you considered pattern matching on the `QueryUnit` instance inside `process`? – Yuval Itzchakov Dec 02 '17 at 15:15
  • Sry, just added more info. I do not wish to mix the two types, I would just like either Simple or Complex queries, but not both. – spyk Dec 02 '17 at 15:17
  • Then have one method for processing `SimpleQuery` and another for `ComplexQuery`? – Yuval Itzchakov Dec 02 '17 at 15:19
  • Yes, that's one solution I've considered, since I really only want one level of nesting. But a) i would like a simpler API and b) might need to support deeper nesting in the future. – spyk Dec 02 '17 at 15:24
  • 1
    Then you have to decide as there are trade offs to each approach. Either go with taking a `Seq[Query]` and pattern match which give you the flexibility of recursively traversing complex queries, or use the simpler approach and take an instance of each in separate methods. At least that's what I see right now from your question. – Yuval Itzchakov Dec 02 '17 at 15:38

1 Answers1

3

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)
  }
}
Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52
  • Probably there is something for this in shapeless too, but this is not very hard to do anyway. – Gábor Bakos Dec 02 '17 at 15:50
  • I think this makes the API non-trivial at all, where OP wants to go for a "simple solution", I don't think this qualifies as simple. – Yuval Itzchakov Dec 02 '17 at 15:57
  • See my comments to the OP in the question: *" a) i would like a simpler API"*. You don't have to go macro level to complicate things :) If OP finds pattern matching an ADT for the underlying type, I hardly think this would qualify as a simpler approach :) – Yuval Itzchakov Dec 02 '17 at 16:07
  • (I have added a cleaned up version. I hope this way it is clearer how this can be used not just for constraining the inputs, but also handling them according to their type.) – Gábor Bakos Dec 02 '17 at 16:58
  • Accepted since it answers the original problem and the theoritical question. However I see it mostly a workaround on the type-system and do not plan on using it on a real life solution if not absolutely necessary. I will probably do the simpler pattern matching version discussed with @YuvalItzchakov, and maybe add some checks on the application side. – spyk Dec 03 '17 at 14:07