Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structured typing in Scala doesn't work with Double?

Tags:

scala

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?

like image 354
Maurício Szabo Avatar asked Oct 04 '12 04:10

Maurício Szabo


1 Answers

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
like image 123
kmizu Avatar answered Nov 03 '22 02:11

kmizu