0
votes

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
I am a Java developer just passing by, but I have guess for You (since Scala run on JVM maybe it can help). In Java there type erasure for generics therefore the type information is present only at compile time. I don't think this is the whole picture but maybe it is related to this behaviour.Zsolt V
val properties[String, Object] = ... is not a valid Scala syntaxOleg Pyzhcov
Yeah I have edited syntax , i forgot the colonSagar Vaghela
"Why object cant accept the java.lang.Double?" It can, but toDouble returns Double and not java.lang.Double.Alexey Romanov
@SagarVaghela with colon it is not valid either.Oleg Pyzhcov

2 Answers

1
votes

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.

1
votes

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.