nirmal
nirmal

Reputation: 107

Compile time error in scala Map while I put an object inside value

I am having one Map containing two Scala objects as value and unique string.

val vv = Map("N"-> Nconstant, "M"-> Mconstant) 

Here the Nconstant and Mconstant are two Objects having constant values in it. After that, I try to access the constant variable inside that object by passing the key below,

val contract = vv("N").contractVal 

contractVal is the variable which has values and is inside both the Mconstant and Nconstant. But IntelliJ is showing

"Cannot resolve symbol contractVal".

Can anyone help with this issue?

Upvotes: 2

Views: 255

Answers (2)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22595

As an addition to Tim's answer, in case you've got types that have a common field but don't have a common type, then you can use duck typing:

object Nconstant {
  val contractVal = "N"
}

object Mconstant {
  val contractVal = "M"
}

val vv = Map("N"-> Nconstant, "M"-> Mconstant, "X" -> Xconstant)

import scala.language.reflectiveCalls

vv("N").asInstanceOf[{ val contractVal: String }].contractVal //N

But beware, it will fail on runtime if N doesn't really have contractVal field!

Upvotes: 2

Tim
Tim

Reputation: 27356

It sounds like Nconstant and Mconstant are different types that happen to have the same field contractVal. If so, you need to determine which type you have by using match:

val contract = vv("N") match {
    case n: Nconstant => n.contractVal
    case m: Mconstant => m.contractVal
  }

This will throw a MatchError if the value is neither Nconstant or Mconstant.

Upvotes: 1

Related Questions