Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object is not a value error in scala

Tags:

object

map

scala

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.

like image 684
Alexandros Avatar asked Jan 31 '12 11:01

Alexandros


People also ask

What is an object in Scala?

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.

What is the difference between state and behavior in 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.

How do you handle errors in Scala?

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]:

How does the “LOAD” statement work in Scala?

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.


2 Answers

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.

like image 82
oxbow_lakes Avatar answered Sep 21 '22 21:09

oxbow_lakes


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

like image 39
Clare Avatar answered Sep 19 '22 21:09

Clare