Understand Scala immutable Map behaviour

125 Views Asked by At

I used a scala immutable map as per below.

val d = "4.55"

  1. This is working fine.

    val  properties = Map("title"->"title" , "value" -> d )
    
  2. Its convert from [String , AnyRef] to [String, Any]

    val  properties = Map("title"->"title" , "value" -> d.toDouble )
    
  3. Cant convert from Double to Object , runtime error

    val  properties:Map[String,Object] = Map("title"->"title" , "value" -> d.toDouble )
    

    Why object cant accept the Double?

  4. Working fine.

    val  properties:Map[String,Object] = Map("title"->"title" , "value" -> d.toDouble.asInstanceOf[Object] )
    

Cant understand the four scenario of Immutable Map behaviour.

2

There are 2 best solutions below

0
On

Most important of all: Scala has no primitive types as Java do.

Scala's Double is a class, inherit from AnyVal, has it's own methods

But Java's Object is the base class of all reference types, aka...Class

So, what you did here is using Object as base class of Double.

In my opinion,
Scala's AnyRef is the corresponding type to Java's Object.
Scala's AnyVal is the corresponding type to Java's Primitive Types.

0
On

As you can see froom the Scala class hierarchy...

Scala class hierarchy

... the Scala equivalent of java.lang.Object is AnyRef, and type String is part of that family, but a Scala Double falls under AnyVal. When the compiler has to reconcile those two types it will find type Any, which can't be promoted to type AnyRef/Object without coercion (i.e. a cast).

If you had d.toSeq instead of d.toDouble the compiler would have gone to AnyRef/Object straight away.