在 Scala 中使用 Java 时,我们必须考虑 null。
例如,HttpServletRequest getter(getAttribute、getHeader 等)都可能返回 null。
我知道我可以在每次调用 HttpServletRequest 方法时手动执行 case/match 或 map 操作,但这有点乏味。此外,像 request.getHeader("Accept-Encoding") 之类的方法调用很麻烦。
我想出了一个丰富的方法来处理这两个问题:
class Servlet_Request_Provides_NullSafe_Getters (r: HttpServletRequest) {
def header(s: String) = Option( r.getHeader(s) )
def attrib(s: String) = Option( r.getAttribute(s) )
def remoteHost = Option( r.getRemoteHost )
def accepts = header("Accept-Encoding")
}
implicit def request2Option(r: HttpServletRequest) =
new Servlet_Request_Provides_NullSafe_Getters(r)
1) 是否有比丰富我的图书馆的另一种/更好的方法来实现相同/相似的效果?
2)如果这是“可行的”方式,那么性能影响/风险是什么?换句话说,是否会被这种模式的明显实用性/便利性烧毁?
对不起,如果这东西很明显,前几天才开始丰富,它看起来真的很有用。只是想确保我在适当的场景中应用模式......
编辑
@dhg 指出 Option.apply() 和:
def safe[T](v: T) = v match {
case null => None
case x => Some(x)
}
是等价的,所以 getter 方法现在使用 Option(f()) 而不是我无关的 safe(f()) 包装器
谢谢