Zee
Zee

Reputation: 1420

Map key not found error despite using option classes

I'm new to the concept of using the Option type but I've tried to use it multiple places in this class to avoid these errors.

The following class is used to store data.

class InTags(val tag35: Option[String], val tag11: Option[String], val tag_109: Option[String], val tag_58: Option[String])

This following code takes a string and converts it into a Int -> String map by seperating on an equals sign.

      val message= FIXMessage("8=FIX.4.29=25435=D49=REDACTED56=REDACTED115=REDACTED::::::::::CENTRAL34=296952=20151112-17:11:1111=Order7203109=CENTRAL1=TestAccount63=021=155=CSCO48=CSCO.O22=5207=OQ54=160=20151112-17:11:1338=5000040=244=2815=USD59=047=A13201=CSCO.O13202=510=127
")
       val tag58 =  message.fields(Some(58)).getOrElse("???")
        val in_messages= new InTags(message.fields(Some(35)), message.fields(Some(11)), message.fields(Some(109)), Some(tag58))
        println(in_messages.tag_109.getOrElse("???"))

where the FIXMessage object is defined as follows:

class FIXMessage (flds: Map[Option[Int], Option[String]]) {
  val fields = flds

  def this(fixString: String) = this(FIXMessage.parseFixString(Some(fixString)))

  override def toString: String = {
    fields.toString
  }
}
object FIXMessage{
  def apply(flds: Map[Option[Int], Option[String]]) = {
    new FIXMessage(flds)
  }

  def apply(flds: String) = {
    new FIXMessage(flds)
  }

  def parseFixString(fixString: Option[String]): Map[Option[Int], Option[String]] = {
     val str = fixString.getOrElse("str=???")
      val parts = str.split(1.toChar)
      (for {
        part <- parts
        p = part.split('=')
      } yield Some(p(0).toInt) -> Some(p(1))).toMap
  }
}  

The error I'm getting is ERROR key not found: Some(58) but doesnt the option class handle this? Which basically means that the string passed into the FIXMessage object doesnt contain a substring of the format 58=something(which is true) What is the best way to proceed?

Upvotes: 0

Views: 852

Answers (1)

Johny T Koshy
Johny T Koshy

Reputation: 3887

You are using the apply method in Map, which returns the value or throw NoSuchElementException if key is not present.

Instead you could use getOrElse like

message.fields.getOrElse(Some(58), Some("str"))

Upvotes: 1

Related Questions