Reputation: 841
I am trying to ensure that classes (which represent some symbolic math expression) with trait Func
possess a method that will return a numerical function (implementing the symbolic expression).
trait Func {
def func[T](x: T): T=>Double
}
case class Const(d: Double) extends Func {
def func[T]: (T=>Double) = (x: T)=>d
}
object Main extends App {
val c = new Const(3.142)
val cAt1 = c.func(1.0)
println(s"c(1.0)=$cAt1") // expected: c(1.0)=3.142
}
This returns the following error:
[error] /projects/tutdiff/diff.scala:6: class Const needs to be abstract, since method func in trait Func of type [T](x: T)T => Double is not defined
[error] case class Const(d: Double) extends Func {
[error] ^
I am interested in why the implementation of func
in Const
doesn't meet the requirements. But also what it is that means a class must be abstract or not (new to Scala).
EDIT: ====================
This is the signature that I was immediately looking for.
trait Func {
def func[T]: T=>Double
}
case class Const(d: Double) extends Func {
def func[T]: T=>Double = (x: T) => d
}
The use of a type parameter T
should probably be the subject of a follow up question.
Upvotes: 1
Views: 259
Reputation: 149538
func
in Func
has the signature:
def func[T](x: T): T => Double
Inside Const
, func
has a different signature:
def func[T]: (T => Double)
It no longer takes a parameter of type T
. Perhaps what you wanted is:
def func[T](x: T): (T => Double) = (x: T) => d
Although I'm not sure what that actually achieves.
Upvotes: 1