在Kotlin中省略的`Return`需要额外的代码。如何解决?

时间:2017-11-07 05:28:28

标签: kotlin

当我在Java(7)中编写Rx Observable时,它如下所示

private Observable observable = Observable.just("http://myurl.com/")
        .map(new Function<String, Person>() {
            @Override
            public Person apply(String url) throws Exception {

                Request request = new Request.Builder().url(url).build();
                Call call = okHttpClient.newCall(request);
                Response response = call.execute();

                if (response.isSuccessful()) {
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        return Person.parseFrom(responseBody.byteStream());
                    }
                }

                return null;
        }
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());

当我将其转换为Kotlin时,如下所示

private val observable = Observable.just("http://myurl.com/")
        .map{
            val request = Request.Builder().url(it).build()
            val call = okHttpClient.newCall(request)
            val response = call.execute()

            if (response.isSuccessful) {
                val responseBody = response.body()
                if (responseBody != null) {
                    Person.parseFrom(responseBody.byteStream())
                } else {
                    null
                }
            } else {
                null
            }
        }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())

在Kotlin版本中,您可能会注意到我有两个null。但是在Java中,我可以避免这样做,因为我可以在Map函数中有一个return语句。我怎么能在Kotlin中实现这一点而不重复null

2 个答案:

答案 0 :(得分:2)

使用qualified return

if (response.isSuccessful) {
    val responseBody = response.body()
    if (responseBody != null)
        return@map Person.parseFrom(responseBody.byteStream())
}
return@map null

答案 1 :(得分:1)

更短

val body = response.body
if (response.isSuccessful && body != null) {
       Person.parseFrom(body.byteStream())
} else null