Object is not a value error in scala

后端 未结 4 719
礼貌的吻别
礼貌的吻别 2020-12-18 21:14

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:

         


        
相关标签:
4条回答
  • 2020-12-18 21:42

    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.

    0 讨论(0)
  • 2020-12-18 21:53

    I got similar error on Lists. try this in scala console:

    import java.util.List object test { def a():List[String] = { val list = List[String](); null }}

    you'll get the err "Object List is not a value."

    You get it because you're hiding the built-in List type, that is because List is different from java.util.List

    What if someone wants to use util.List?

    you can use a qualified name or a rename import

    ! import java.util.{List => JList}

    import java.util.{List=>JList}

    0 讨论(0)
  • 2020-12-18 21:57

    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

    0 讨论(0)
  • 2020-12-18 22:05

    Because in scala each native scala class comes with an (optional) companion object (allowing for assignment from the companion object as in your example code) when incorporating a java class into scala code always remember to instantiate the class by invoking the constructor, ie. use keyword "new", thus creating a value.

    0 讨论(0)
提交回复
热议问题