Scala implicit primitive conversion to AnyRef

In Scala I have the code that I am writing Map[String, AnyRef]. When I try to initialize the map using the following, Scala complains that it expects Map[String, AnyRef], but the value is 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 the area:

implicit def booleanToAnyRef(value: Boolean): AnyRef = value.asInstanceOf[AnyRef]

but the compiler is still complaining.

Should the compiler use an implicit method to convert primitive boolean values ​​to values AnyRef? Is there any way (ugly) x.asInstanceOf[AnyRef]to convert this data?

+5
source share
3 answers

For the record, as other answers show, the last compiler will say:

: scala.Boolean = > java.lang.Boolean, , , . , scala.Boolean AnyRef. , : x: java.lang.Boolean.

, , , , .

+6

, java booleans:

scala> def foo(x: AnyRef) = x.toString
foo: (x: AnyRef)java.lang.String

scala> foo(true: java.lang.Boolean)
res0: java.lang.String = true

:

scala> implicit def b2B(x: Boolean) = java.lang.Boolean.valueOf(x)
//foo: (x: Boolean)java.lang.Boolean

scala> foo(true)
//res1: java.lang.Boolean = true

( ) :

scala> 1.underlying
//res2: AnyRef = 1
+1

You should avoid such implicit conversions between generic types (and the compiler suggests this). If you want to use java.lang.Booleaninstead scala.Boolean, you can do it like this:

import java.lang.Boolean._
val myMap: Map[String, AnyRef] = Map("foo" -> TRUE, "bar" -> FALSE)
0
source

All Articles