[英]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: 我对此解决方案有一些疑问:
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.