Mark
Mark

Reputation: 379

How to extends an abstract class with generics?

I am new to Scala. What I want to do is to create an abstract class named EnhancedFirstOrderMinimizer which extends another abstract class named FirstOrderMinimizer. However, the IDE tells me that "Type mismatch, expected: nothing, actual: DF".

Here is FirstOrderMinimizer:

abstract class FirstOrderMinimizer[T, DF <: StochasticDiffFunction[T]]
    (maxIter: Int = -1, tolerance: Double = 1E-6, improvementTol: Double = 1E-3,
     val minImprovementWindow: Int = 10,
     val numberOfImprovementFailures: Int = 1)
    (implicit space: NormedModule[T, Double])
    extends Minimizer[T, DF] with SerializableLogging {

protected def initialHistory(f: DF, init: T): History
  ...
  type History
  protected def initialHistory(f: DF, init: T): History
  protected def adjustFunction(f: DF): DF = f
  protected def adjust(newX: T, newGrad: T, newVal: Double): (Double, T) =
    (newVal, newGrad)
  protected def chooseDescentDirection(state: State, f: DF): T
  protected def determineStepSize(state: State, f: DF, direction: T): Double
  protected def takeStep(state: State, dir: T, stepSize:Double): T
  protected def updateHistory(newX: T, newGrad: T, newVal: Double,
                              f: DF, oldState: State): History

  def iterations(f: DF, init: T): Iterator[State] = {
    val adjustedFun = adjustFunction(f)
    infiniteIterations(f, initialState(adjustedFun, init))
      .takeUpToWhere(_.converged) 
  }
  ...
}

Here is EnhancedFirstOrderMinimizer:

EnhancedFirstOrderMinimizer[T, DF<:StochasticDiffFunction[T]]
    (maxIter: Int = -1, tolerance: Double=1E-6, improvementTol: Double=1E-3)
    extends FirstOrderMinimizer {

  override def iterations(f: DF, init: T): Iterator[State] = {
    val adjustedFun = adjustFunction(f)

    // f: Type mismatch, expected: nothing, actual: DF
    infiniteIterations(f, initialState(adjustedFun, init))
      .takeUpToWhere(_.converged)
  }
}

Could you please help me check it out?

Upvotes: 1

Views: 180

Answers (1)

Chris Martin
Chris Martin

Reputation: 30756

The compiler is telling you that f is the wrong type for the first argument of infiniteIterations. We probably need to see where infiniteIterations is declared to know exactly what's going on.

But I think the quick answer to your extension problem is that extends FirstOrderMinimizer should be changed to extends FirstOrderMinimizer[T, DF].

Upvotes: 2

Related Questions