Scala 不可变泛型类的类型特定函数

Scala 不可变泛型类的类型特定函数,scala,generics,types,containers,Scala,Generics,Types,Containers,假设我有一个Container\u Generic[T]Generic类,我希望特定的函数仅在T为Double时可用 有没有一种方法可以做到这一点而不需要可变性或创建子类 我之所以这样问是因为子类需要大量不必要的代码重复。见下例: class Container_Generic[T](x: Seq[T]){ def map(f: T => T): Container_Generic[T] = new Container_Generic[T](x map f) // def max:

假设我有一个
Container\u Generic[T]
Generic类,我希望特定的
函数
仅在
T
Double
时可用

有没有一种方法可以做到这一点而不需要可变性或创建子类

我之所以这样问是因为子类需要大量不必要的代码重复。见下例:

class Container_Generic[T](x: Seq[T]){
  def map(f: T => T): Container_Generic[T] = new Container_Generic[T](x map f)
  // def max: Double = x.max //<-Impossible to implement unless T pre-specified
}

class Container_Double_works(x: Seq[Double]) extends Container_Generic[Double](x){
  override def map(f: Double => Double): Container_Double_works = new Container_Double_works(x map f)
  def max: Double = x.max
}

class Container_Double_doesntWork(x: Seq[Double]) extends Container_Generic[Double](x){
  def max: Double = x.max
}

// Work
val C_base = new Container_Generic[Int](Seq(1)).map(_*2) // : Container_Generic[Int]
val C_double = new Container_Double_works(Seq(1)).map(_*2) // : Container_Double_works

// Don't work correctly: No longer same class
val C_double_doesntWork = new Container_Double_doesntWork(Seq(1)).map(_*2) // : Container_Generic
class容器\u泛型[T](x:Seq[T]){
定义映射(f:T=>T):容器\u通用[T]=新容器\u通用[T](x映射f)
//def max:Double=x.max//Double:Container\u Double\u works=新Container\u Double\u works(x映射f)
def max:Double=x.max
}
类Container\u Double\u doesnetwork(x:Seq[Double])扩展Container\u Generic[Double](x){
def max:Double=x.max
}
//工作
val C_base=new Container_Generic[Int](Seq(1)).map(*2)/:Container_Generic[Int]
val C_double=新的容器_double_工程(序号(1)).map(*2)/:容器_double_工程
//工作不正常:不再是同一个类
val C_double_doesnetwork=新容器_double_doesnetwork(Seq(1)).map(*2)/:容器_Generic

我对Scala还是新手,所以我可能采取了错误的方法,或者可能只是不知道正确的术语。

使用Scala impicits几乎可以完成所有操作

class Container_Generic[T](val x: Seq[T]) {
    def map(f: T => T): Container_Generic[T] = new Container_Generic[T](x map f)
}

implicit class WithMax(val c: Container_Generic[Double]) {
    def max: Double = c.x.max
}

val cDouble: Container_Generic[Double] = new Container_Generic(Seq(1.12))
val cString: Container_Generic[String] = new Container_Generic(Seq("12"))
println(cDouble.max)
//won't compile
//  println(cString.max)

如果用max将
标记为隐式,则可以删除
toBetterType
。它可以工作,但不在顶层。它将给出
“隐式”修饰符不能用于顶级对象,否则会出错。好答案。