prosseek
prosseek

Reputation: 190809

Type mismatch error in initialization of Scala map (string to object)

I need to setup a Scala Map that maps from String to an object (string, integer, floating point number)

I tried this code:

val m = Map[String, Object]("A"->10, "B"->20.5)

to get type mismatch error.

enter image description here

What could be the solution to this issue?

Upvotes: 1

Views: 1489

Answers (1)

Ende Neu
Ende Neu

Reputation: 15783

Strictly speaking Scala Int is not a subtype of Object, but it is a subtype of AnyVal:

val m = Map[String, AnyVal]("A"->10, "B"->20.5)

Where AnyVal is a common super type of all Scala primitives, I always refer to this image which illustrates the type hierarchy:

enter image description here
(source: verrech.net)

If you want a common supertype with scala.Scala.Object or of java.lang.Object use Any.

Here is the link to the image.

Upvotes: 11

Related Questions