Home > Mobile >  Scala: How to get all keys from Option[Map[String, Int]]?
Scala: How to get all keys from Option[Map[String, Int]]?

Time:05-18

I have this val: val offsets: Option[Map[String, Int]] = jsonOffsets.get(topic)

How do I get all the keys from offsets? Is it offsets[0], offsets.keys isn't working.

CodePudding user response:

offsets is an Option, so it may or may not contain a Map. Use pattern matching to handle that:

offsets match {
    case Some(map) => // Whatever you want to do with the map
    case None => // What should you do when there's no map?
}

If you don't know about options, this is a good read.

  • Related