Reputation: 2613
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
Reputation: 4470
There's several issues.
, your map is immutable, you can't put things inside a immutable map.
val map : mutable.Map[Int, TestClass] = mutable.Map[Int, TestClass]()
is case Some(x)=> {//dosomething
Since the return is an Option, you need a Some type to match against.
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
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