views:

191

answers:

2

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?
+6  A: 

Scala's built-in Option is what you're setting out to reinvent.

In that case:

scala> val sOpt: Option[String] = Option(null)
sOpt: Option[String] = None
Randall Schulz
He knows about the Option class already. He wants a function that makes the conversion easy.
Ken Bloom
I could not get that code to work on Scala-2.7.5.
Thomas
`val sOpt1: Option [String] = None` and `val sOpt2: Option [String] = Some ("foo")` should do it.
user unknown
better: `def mb (s: String) : Option [String] = if (s != null) Some (s) else None` would do it on 2.7.7
user unknown
@Thomas: So many things are so much better in 2.8. This is just one among many.
Randall Schulz
@Randall Can't wait for it to come out. But since I have a application in "production", I'm still on 2.7.7.
Thomas
+1  A: 

Why bother making a whole companion object out of it? It's just a function, so you don't need to implement it as an object that looks like a function.

object MyUtilities{
  // a whole bunch of other utilities that you use all over can also be put in this class.
  def maybe[T](t:T) = if (t==null) None else Some(t)
}
Ken Bloom