简体   繁体   English

为什么特征不能具有上下文边界参数

[英]Why can't traits have parameters with Context Bounds

Here :ClassTag : TypeTag base class definitions are not allowed on traits as they are considered as Context Bounds 在这里:ClassTag:TypeTag基类定义不允许在特征上使用,因为它们被视为上下文界限

I can make it Abstract Class but I loose the benefit of multi-inheritance 我可以使它成为抽象类,但是我失去了多重继承的好处

import scala.reflect.ClassTag
import reflect.runtime.universe.TypeTag
import org.apache.spark.sql.Dataset

trait DataProcessor[T <: Product : ClassTag : TypeTag, U <: Product : ClassTag : TypeTag] {
  def performAnalysis(inputDs: Dataset[T]): Dataset[U]
}

This is due to the fact that Scala doesn't allow a trait to receive arguments as they don't have a constructor (this might change in the upcoming future ). 这是由于以下事实:Scala不允许特征接受参数,因为它们没有构造函数(这可能会在将来出现 )。 An expansion of context bounds is to add implicit parameters to the definition. 上下文边界的扩展是在定义中添加隐式参数。 Thus, you're actually trying to write: 因此,您实际上是在尝试编写:

trait DataProcessor[T <: Product, U <: Product](implicit ev: ClassTag[T], ev1: TypeTag[U], ...)

Instead, you can require them as abstract type members on the trait: 相反,您可以要求它们作为特征上的抽象类型成员

trait DataProcessor[T <: Product, U <: Product] {
  def typeTagU: TypeTag[U]
  def clsTagU: ClassTag[U]
  def typeTagT: TypeTag[T]
  def clsTagT: ClassTag[T]

  def performAnalysis(inputDs: Dataset[T]): Dataset[U]
}

Or, as Luis mentioned, move the implicits to where you actually require them, at the method level: 或者,如Luis所述,将隐式方法移到方法级别的实际位置:

def performAnalysis(inputDs: Dataset[T])(implicit ev: ClassTag[T], ev1: TypeTag[T]): Dataset[U]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM