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

时间:2015-06-19 14:22:33

标签: scala generics types containers

假设我有一个Container_Generic[T]泛型类,并且我希望只有functionsT时才能使用特定的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

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

1 个答案:

答案 0 :(得分:3)

你几乎可以用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)
相关问题