Take this code:
class Register(var value:Int = 0) {
def getZeroFlag() : Boolean = (value & 0x80) != 0
}
object Register {
implicit def reg2int(r:Register):Int = r.value
implicit def bool2int(b:Boolean):Int = if (b) 1 else 0
}
I want to use it like so:
val x = register.getZeroFlag + 10
but I am greeted with:
type mismatch; found : Boolean required: Int
What goes? Do I need to define a implicit taking a function that returns a bool?
Here’s an example demonstrating how to use your implicits:
Two potentially non-obvious things here:
Register, the compiler will look in the companion objectRegister. This is why we didn’t need to bringreg2intexplicitly into scope for definingxandy. However, the conversionbool2intdoes need to be in scope because it’s not defined on theBooleanorIntcompanion object.+is already defined on all objects to mean string concatenation via the implicitany2stringaddinscala.Predef. The definitionval zis illegal because the implicit for string concatenation takes priority overreg2int(implicits found in companion objects are relatively low priority). However, the definitionval z2works because we’ve broughtreg2intinto scope, giving it higher priority.For more details about how the compiler searches for implicits, see Daniel Sobral’s very nice explanation: Where does Scala look for implicits?