我依赖于旧的Java API,它有点糟糕,并且喜欢在数据丢失时抛出空指针异常。我想创建一个具有选项类型访问器的子类,但保留旧访问器,直到我决定需要为它们创建安全访问器。有没有一种从原始对象的副本创建子类的好方法?我希望实现以下目标:
SafeIssue extends Issue {
def safeMethod: Option[Value] = { //... }
}
val issue = oldapi.getIssue()
val safeIssue = SafeIssue(issue)
//Preserves issue's methods and data if I need them
val unsafeVal = safeIssue.unsafeMethod
val maybeVal = safeIssue.safeMethod
答案 0 :(得分:4)
为什么不尝试隐式转换呢?这对于喜欢创建自己的对象的Java API更有效。所以你会
class SafeIssue(issue: Issue) {
def original = issue
def safeFoo = Option(issue.foo)
// ... You must write any of these you need
}
implicit def make_issues_safe(issue: Issue) = new SafeIssue(issue)
然后你可以 - 只要你提供了方法 - 写了像
这样的东西val yay = Issue.myStaticFactoryMethodThing.safeFoo.map(x => pleaseNoNull(x))
(然后,您可以决定是否要在代码中携带SafeIssue
或Issue
,并始终可以从Issue
取回SafeIssue
original
方法(或者您可以将issue
参数设为val
。)