简体   繁体   English

Maybes是scala的良好模式吗?

[英]Are Maybes a good pattern for scala?

For a while I have been struggling to integrate scala with java methods that might return null. 一段时间以来,我一直在努力将scala与可能返回null的java方法集成在一起。 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? 此功能是否隐藏了陷阱?

Scala's built-in Option is what you're setting out to reinvent. Scala的内置Option是您要重新发明的。

In that case: 在这种情况下:

scala> val sOpt: Option[String] = Option(null)
sOpt: Option[String] = None

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM