Scala Seq - 只接受相同子类型的元素 [英] Scala Seq - accept only elements of the same subtype

查看:70
本文介绍了Scala Seq - 只接受相同子类型的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个如下所示的类型层次结构:

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

是否可以创建一个接受 Seq[Color] 的方法,该Seq[Color] 包含所有 Red 或所有 Green 的元素,但不是两者都有?

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?

例如在以下代码中:

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

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

[T] 应该怎么做才能使上面的代码不进行类型检查?

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

编辑

最初的问题如下:我正在尝试为嵌套查询设计一个 JSON API.我提出了以下设计:

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

Map 的元素将是合取 (AND),而 Seq 的元素将是析取 (OR).我不想将 Simple 与 ComplexQueries 混合使用,我打算在 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].

推荐答案

试试这个(部分基于 这篇来自 Miles Sabin 的博文):

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))))

不理想(名字错误,没有@implicitNotFound注解).

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.

一个清理过的版本:

@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))))

或者使用类型边界和隐式:

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)
  }
}

这篇关于Scala Seq - 只接受相同子类型的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆