Scala implicit conversion of primitive to AnyRef

11,256

Solution 1

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.

Solution 2

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)
Share:
11,256
Ralph
Author by

Ralph

Physician, retired. Retired software engineer/developer (Master of Science in Computer Science). I currently program mostly in Go. I am particularly interested in functional programming. In past lives, I programmed in Java, Scala, Basic, Fortran, Pascal, Forth, C (extensively, at Bell Labs), C++, Groovy, and various assembly languages. Started programming in assembly language in 1976. I started a martial arts school in 1986 (Shojin Cuong Nhu in New Jersey) and currently teach at the Tallest Tree Dojo in Gainesville, Florida. I like to cook. I am an atheist. Email: user: grk, host: usa.net

Updated on June 17, 2022

Comments

  • Ralph
    Ralph almost 2 years

    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?