Are Maybes a good pattern for scala?

Posted by Fred Haslam on Stack Overflow See other posts from Stack Overflow or by Fred Haslam
Published on 2010-06-01T00:57:05Z Indexed on 2010/06/01 1:03 UTC
Read the original article Hit count: 287

Filed under:
|
|
|
|

For a while I have been struggling to integrate scala with java methods that might return null. I came up with the following utility which helps a lot:

// produce an Option, nulls become None
object Maybe {
    def apply[T](t:T) = if (t==null) None else Some(t)
}

Maybe(javaClass.getResultCouldBeNull()).map( result => doSomeWork(result) )

I have a few questions about this solution:

  1. Is there a better or more standard pattern to use?
  2. Am I duplicating something that already exists?
  3. Does this functionality have hidden gotchas?

© Stack Overflow or respective owner

Related posts about java

Related posts about scala