Sandy
Sandy

Reputation: 2613

How to match value from scala Map


I am new to scala and was working with Maps. I do a get on Map, but I am not sure how to check for the return type and use it.
I have following code which gives following compilation error "Pattern Type is incompatible with expected Type: TestClass.type required Option[TestClass].

object MapOptionUsage extends App {
 val map : Map[Int, TestClass] = Map[Int, TestClass]() 
 var i = 0
 for(i <- 0 to 5){
   map.put(i, createObj(i))
 }
 var a = map.get(5)

 a match {
     case TestClass => {//dosomething
    }
     case None => {//dosomething
    }
   }
   def createObj(i: Int): TestClass = {
     return new TestClass(i)
  }
}
case class TestClass(val id: Int)

Upvotes: 1

Views: 1504

Answers (2)

Ryan Leach
Ryan Leach

Reputation: 4470

There's several issues.

  1. , your map is immutable, you can't put things inside a immutable map. val map : mutable.Map[Int, TestClass] = mutable.Map[Int, TestClass]()

  2. is case Some(x)=> {//dosomething Since the return is an Option, you need a Some type to match against.

  3. is def createObj(i: Int): TestClass = { needs to be defined on your object, not inside your match statement.

Edit: To address comments.

case Some(x)=> {//dosomething
    System.out.println(x.id)
}

Will match and create a new value, where x is equal to the contents of Some, that is, the TestClass contained inside the map.

Upvotes: 1

jwvh
jwvh

Reputation: 51271

get() returns Option[], and TestClass takes a constructor parameter, so you have to match for both those things.

case Some(TestClass(x)) => {//dosomething

BTW, good Scala code doesn't use var or return.

Upvotes: 2

Related Questions