I'm trying to do the following code:
def sum(e: { def *(x: Double): Double}) = e * 2.0
Problem is, this doesn't work with any numeric classes:
sum(20.0)
<console>:9: error: type mismatch;
found : Double(10.0)
required: AnyRef{def *(x: Double): Double}
algo(10.0)
sum(10)
<console>:9: error: type mismatch;
found : Int(10)
required: AnyRef{def *(x: Double): Double}
algo(10)
Is there something wrong with my code?
Scala's structural type doesn't require AnyRef.
Certainly, the following method declaration doesn't work as expected.
def sum(e: { def *(x: Double): Double }) = e * 2.0
The reason of that is the above code is interpreted as the followings:
def sum(e: AnyRef { def *(x: Double): Double}) = e * 2.0
If you specify Any explicitly, the code works:
scala> def sum(e: Any { def *(x: Double): Double }) = e * 2.0
sum: (e: Any{def *(x: Double): Double})Double
scala> sum(10.0)
res0: Double = 20.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With