可选项化的Java getter [英] Option-izing Java getters

查看:89
本文介绍了可选项化的Java getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中使用Java时,我们必须考虑null.

When working with Java from Scala, we have to account for null.

HttpServletRequest getter(getAttribute,getHeader等)都可能返回null.

HttpServletRequest getters (getAttribute, getHeader, etc.) for example, all potentially return null.

我知道我可以在对HttpServletRequest方法的每次调用中手动执行大小写/匹配或映射操作,但这有点乏味.另外,诸如request.getHeader("Accept-Encoding")之类的方法调用也很麻烦.

I know I can manually do a case/match or map operation on each call to an HttpServletRequest method, but that's a bit tedious. Also, method calls like request.getHeader("Accept-Encoding") are a mouthful.

我想出了丰富的方法来处理这两个问题:

I came up with an enrichment to handle both issues:

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)如果这是可行的"方法,那么对性能的影响/风险是什么?换句话说,这种模式的明显实用性/便利性会让人感到厌倦吗?

1) Is there another/better way than enrich-my-library to achieve the same/similar affect?
2) If this is "the" way to go, what are the performance impacts/risks? In other words, can one get burned by the apparent utility/conveniences of this pattern?

很抱歉,如果这些内容很明显,只是在第二天才开始充实,这确实很有用.只是要确保我在适当的情况下应用该模式...

Sorry if this stuff is obvious, only just started enriching the other day, and it really seems quite useful. Just want to make sure I'm applying the pattern in the proper scenarios...

编辑
@dhg指出Option.apply()和:

EDIT
@dhg pointed out that Option.apply() and:

def safe[T](v: T) = v match {
  case null => None
  case x => Some(x)
}

是等效的,因此getter方法现在使用Option(f())而不是我的无关紧要的safe(f())包装器

are equivalent, so the getter methods now use Option(f()) instead of my extraneous safe(f()) wrapper

谢谢

推荐答案

在评论中已经提到:

def safe[T](v: T) = Option(v)

Option(v)等效于:

v match {
  case null => None
  case x    => Some(x)
}

safe方法也不必要地是公共的,并且是类的一部分.我建议简单地对其进行内联.

Also the safe method is unnecessarily public and part of the class. I would suggest simply inlining it.

2)如果这是可行的"方法,那么对性能的影响/风险是什么?

2) If this is "the" way to go, what are the performance impacts/risks?

通常,使Java旧版API适应性地利用Option是一个好主意.我经常使用可以返回nullEntityManager.find()进行此操作.

Generally adapting Java legacy APIs to utilize Option is a good idea. I do this often with EntityManager.find() that can return null.

您的隐式转换也可以.但是,请勿在类名中使用下划线,Java/Scala命名约定更喜欢CamelCase.

Your implicit conversion is also fine. However don't use underscores in class names, Java/Scala naming conventions prefer CamelCase.

这篇关于可选项化的Java getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆