While trying to make a map in Scala, I receive the following error message: object Map is not a value
The code I'm using is the following:
val myStringMap = Map[String, String]("first" -> "A", "second" -> "B", "third" -> "C")
I am quite puzzled as to why I cannot create this map because after looking at Scala documentation, it seems to me that the syntax of my code is proper.
The object in any programming language consists of identity, behavior, and state we will discuss them in detail in the coming section. The object can be created by using the new keyword in the scala.
Scala Object 1 Identity: This is used to give a unique name to our class object. ... 2 State: State is a property of an object and it is presented by the attributes. This defined the attribute of the object what this object actually is. 3 Behavior: This is used to represent the method of the object which defined what the object actually does.
We already demonstrated one of the techniques to handle errors in Scala: The trio of classes named Option, Some, and None. Instead of writing a method like toInt to throw an exception or return a null value, you declare that the method returns an Option, in this case an Option [Int]:
Since :load works line-by-line, just as if you were typing at the REPL, when the interpreter sees it's done: that is a perfectly valid, complete Scala declaration of a (not terribly interesting) object. The opening brace on the next line will start a new block that is unrelated to the object you've just defined.
When you see the error "object is not a value" this typically means that the in-scope type is a Java type - you probably are importing java.util.Map
in scope
scala> Map(1 -> "one")
res0: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 -> one)
But
scala> import java.util.Map
import java.util.Map
scala> Map(1 -> "one")
<console>:9: error: object Map is not a value
Map(1 -> "one")
^
Remember, in scala each class comes with a (optional) companion object which is a value. This is not true of Java classes.
Just found this so maybe it will be useful to share my solution. If you have imported java.util.Map and need to use scala.collection.immutable.Map then use it with the full name so instead of
Map(1 -> "one")
do
scala.collection.immutable.Map(1 -> "one")
This way it will know what you mean
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With