我依靠的是一个旧的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 themval unsafeVal = safeIssue.unsafeMethodval maybeVal = safeIssue.safeMethod 最佳答案 为什么不尝试隐式转换呢?这与喜欢创建自己的对象的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(或者可以将参数a issue。) 10-08 11:35