Home > Mobile >  Length of values in a Scala Map
Length of values in a Scala Map

Time:11-30

I have a simple map as below

val myMap = Map("A" -> "AB300","B" -> "XI134","C" -> null)

I would like to validate the length of a particular key and would like to return the value as string (and not as Option . I tried the following

myMap.getOrElse("A",null).toString.length
val res50: Int = 5

This works fine. But obviously, doesn't handle for null data

myMap.getOrElse("C",null).toString.length 
//Null pointer Exception

Is there a way to handle null too? The expectation is length for a null value should return zero (may be replacing null with space or something)

CodePudding user response:

You almost never need to use nulls in Scala, Option is great I don't see why you are insisting on not using it. Anyway, this is probably what you're looking for:

myMap.get("C")
  .flatMap(Option.apply) // since some values are null in your map
  .fold(ifEmpty = 0)(s => s.length)

CodePudding user response:

Another solution:

util.Try(myMap("D").length).getOrElse(0)
  • Related