Home > Blockchain >  No Result using Object in Scala
No Result using Object in Scala

Time:06-17

I am trying to print the value of 1, 2 or 3 using this code

but it just says

defined object Demo

import scala.collection.immutable._

object Demo {
  val mymap : Map[String, String] =
  Map("1" -> "ME", "2" -> "SUPERMAN", "3" -> "ZOD")
  def main(args: Array[String]) {
  
    println(mymap("1"));
    
  }
    
  
}

CodePudding user response:

Judging from the tags you used (databricks), it looks like you are using either a REPL or some other online worksheet. As such, you don't have to create an object with a main method, but just write in your code, as follows:

import scala.collection.immutable._

val mymap: Map[String, String] =
  Map("1" -> "ME", "2" -> "SUPERMAN", "3" -> "ZOD")

println(mymap("1"))

You can play around with this code with another Scala online worksheet, called Scastie (here).

Alternatively, you can also call Demo.main directly from outside of the object definition, passing Array.empty as its only argument.

A few of further notes:

  • I'm not 100% whether this is true for your environment, but in general importing scala.collection.immutable._ is not strictly necessary
  • in Scala you can make use of type inference and skip the Map[String, String] type annotation: the compiler will infer it for you
  • semi-colons are optional in Scala

CodePudding user response:

I am assuming you are running this code in an IDE such as IntelliJ IDEA. Just change the println statement to list all the values in your Map using the values method:

object Demo {
  val mymap: Map[String, String] =
    Map("1" -> "ME", "2" -> "SUPERMAN", "3" -> "ZOD")

  def main(args: Array[String]) = {

    println(mymap.values)
  }
}

You should get:

Iterable(ME, SUPERMAN, ZOD)

In case you are running the code in the Scala interpreter, you don't need to create an object with a main method. You can directly type in the code that you are interested in testing. Simply write your Map definition there and call values on it, and the interpreter will output it automatically:

scala> val mymap = Map("1" -> "ME", "2" -> "SUPERMAN", "3" -> "ZOD")
val mymap: scala.collection.immutable.Map[String,String] = Map(1 -> ME, 2 -> SUPERMAN, 3 -> ZOD)

scala> mymap.values
val res0: Iterable[String] = Iterable(ME, SUPERMAN, ZOD)
  • Related