Elegant way handling both missing key and null values from Scala Map -


i understand

  • in scala use of null should avoided
  • and map.get return option[b] , can use .getorelse value , fallback default value

e.g.

map.getorelse("key1","default") 

meanwhile interacting java library, values null.

e.g. map("key1"->null)

getorelse throw null pointer in case.

i want handle both cases , result in writing this

  def getorelsenonull[a,b](map:map[a,b],key:a,default:b) = {     map.get(key) match{       case some(x) if x != null => x       case _ => default     }   } 

which quite ugly. (it map[any] , need string key)

getorelsenonull(map,"key1","").asinstanceof[string]) 

is possible use implicit extend map, or other elegant way?

if you're dealing immutable map, safest thing filter out null values front (this incurs creation of yet map instance, unless have specific reason care performance here should not issue).

val withoutnulls = map.filter{case (k,v)=> v != null} 

any key holding null gone, , such getorelse on key return none. trivial, , job once all.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -