In Scala code that I am writing, I have a Map[String, AnyRef]
. When I try to initialize the Map using the following, Scala complains that it is expecting a Map[String, AnyRef]
but the value is a Map[String, Any]
:
val myMap: Map[String, AnyRef] =
Map("foo" -> true, "bar" -> false)
I know that I can use the following instead:
val myMap: Map[String, AnyRef] =
Map("foo" -> true.asInstanceOf[AnyRef], "bar" -> false.asInstanceOf[AnyRef])
I declared the following in scope:
implicit def booleanToAnyRef(value: Boolean): AnyRef = value.asInstanceOf[AnyRef]
but the compiler still complains.
Shouldn't the compiler use the implicit method to convert the primitive boolean values into AnyRef
values? Is there any way, short of (the ugly) x.asInstanceOf[AnyRef]
to have these converted?
For the record, as the other answers suggest, the latest compiler will say:
Note: an implicit exists from scala.Boolean => java.lang.Boolean, but methods inherited from Object are rendered ambiguous. This is to avoid a blanket implicit which would convert any scala.Boolean to any AnyRef. You may wish to use a type ascription:
x: java.lang.Boolean
.
The latest compiler will always be a friend who gives better advice than the friend you used to hang with and get into trouble together with.
You should avoid such implicit conversions between general types (and compiler suggests it). If you want to use java.lang.Boolean
instead of scala.Boolean
you can do it this way:
import java.lang.Boolean._
val myMap: Map[String, AnyRef] = Map("foo" -> TRUE, "bar" -> FALSE)
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