Can anyone enlighten me as to why implicit type conversion does not work with ==
?
Example:
class BitArray(l: Int, v: Long) {
val length = l
var value = v
def ==(that: BitArray) = value == that.value
def ==(integer: Long) = value == integer
def +(that: BitArray) = new BitArray(length,value+that.value )
def +(integer: Long) = new BitArray(length,value+integer )
//...
}
object BitArray{
implicit def longToBitArray(x : Long) = new BitArray(64,x)
def apply(v: Long) :BitArray = apply(64,v)
}
Now I can do:
scala> BitArray(5) + 5
res13: BitArray = 00000000000000000000000000001010
scala> 5 + BitArray(5)
res14: BitArray = 00000000000000000000000000001010
scala> BitArray(5) == 5
res15: Boolean = true
scala> BitArray(5) == 6
res16: Boolean = false
BUT:
scala> 5 == BitArray(5)
<console>:11: warning: comparing values of types Int and BitArray using `==' will
always yield false
5 == BitArray(5)
^
res17: Boolean = false
Implicit conversions in Scala are the set of methods that are apply when an object of wrong type is used. It allows the compiler to automatically convert of one type to another. Implicit conversions are applied in two conditions: First, if an expression of type A and S does not match to the expected expression type B.
Type conversion (or typecasting) means transfer of data from one data type to another. Implicit conversion happens when the compiler (for compiled languages) or runtime (for script languages like JavaScript) automatically converts data types. The source code can also explicitly require a conversion to take place.
An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.
The process of converting one type of object and variable into another type is referred to as Typecasting. When the conversion automatically performs by the compiler without the programmer's interference, it is called implicit type casting or widening casting.
You are missing a fundamental aspect of Scala, which is how equality works.
Basically, all classes extending AnyRef
implement the following method:
def equals (arg0: Any) : Boolean
And all classes implement the following method:
def == (arg0: Any) : Boolean
Now, you should override not ==
, but equals
. The method ==
will call equals
, but Java code will use equals
, not ==
. This is not the cause of the problem you see, but it is important enough that I think it is worth mentioning.
Now, as to the implicit not working, remember that implicits are only looked for if there is no method that satisfy your code. However, Int
's ==
can be compared with BitArray
, as ==
receives an argument of type Any
. Therefore, Int
's equality method is called, and no implicit is looked for.
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