Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala implicit conversion of primitive to AnyRef

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?

like image 753
Ralph Avatar asked Sep 27 '12 17:09

Ralph


2 Answers

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.

like image 187
som-snytt Avatar answered Oct 03 '22 16:10

som-snytt


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)
like image 44
Sergey Passichenko Avatar answered Oct 03 '22 16:10

Sergey Passichenko