可选<>和返回类型变窄 [英] Optional<> and return type narrowing

查看:83
本文介绍了可选<>和返回类型变窄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中< 8,返回不安全"对象(objects或null),我能够在子类中专门化返回类型:

In Java < 8, returning "unsafe" objects (objects or null), I was able to specialize return type in subclass:

class A {}
class B extends A {}
interface Sup { A a(); /* returns A instance, or null */ }
interface Sub extends Sup { B a(); }

在Java 8中,如果我想使我的API更安全",则应该返回Optional<A>而不是"raw" A:

In Java 8, if I want to make my API "safer", I should return Optional<A> instead of "raw" A:

interface Sup { Optional<A> a(); }
interface Sub extends Sup { Optional<B> a(); }

但是不能编译!因为Optional<B>不是Optional<A>的子类.

But doesn't compile! Because Optional<B> is not a subclass of Optional<A>.

我应该如何解决此问题?

How I'm supposed to resolve this issue?

推荐答案

您可以使用通配符.

interface Sup { Optional<? extends A> a(); }

interface Sub extends Sup { Optional<? extends B> a(); }

我本可以将其设置为Optional<B>,但是使用Optional<? extends B>允许另一个接口扩展Sub并执行相同的操作.

I could have made it just Optional<B> but using Optional<? extends B> allows another interface to extend Sub and do the same thing.

我个人认为这有些混乱,最好在必要时只返回ABnull.

Personally, I think this is a bit of a mess, and it would be preferable to just return A or B, or null where necessary.

这篇关于可选&lt;&gt;和返回类型变窄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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