scalascalacscala-compiler

Is there scala compiler option that makes ` Option[T](t).map(x => null)` return None instead of Some(null)


I've enterprise polyglot codebase which is made of java and scala.

We have lot of places where we do map function on Option[T] and the mapping function is legacy code which returns null.

Option(2).map(x => null) returns Some(null). when another higher order function is applied on the result it throws NullPointerException.

As a workaround we do Option[T](t).map(x => Option(mapping(x))) in order to make this result None. It is slowly becoming code smell.

I'm trying to see whether there is any better way to do this or there is scala compiler option that return None when the calls like this Option[T](t).map(x => null) are made automagically.


Solution

  • Personally I don't think there is much wrong with your workaround given you have to work with legacy APIs that return null but you have to flatMap it like so

    Option(t).flatMap(x => Option(legacyJavaFunc(x)))
    

    You could invest in a Scala wrapper layer which handles dealing with nulls and exceptions behind the scenes so then you don't have to call Java API directly

    // Scala API layer over Java API
    def scalaFunc[T](t: T): Option[T] = Option(legacyJavaFunc(t))
    
    // so we can avoid calling Java API directly
    Option(t).flatMap(scalaFunc)
    

    Execution of legacyJavaFunc happens at run-time so compiler cannot predict the result in advance at compile-time to rewrite it automagically.