我如何使用let检查2个条件(或应用等) [英] How can I check 2 conditions using let (or apply etc)

查看:112
本文介绍了我如何使用let检查2个条件(或应用等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更惯用的方式写以下内容?

Is there a more idiomatic way to write the following?

foo?.let{
        if(!foo.isBlank()) {
            bar?.let { 
                if(!bar.isBlank()) {
                    println("foo and bar both valid strings")
                }
            }
        }
    }

基本上,这个想法是两个字符串都应该是nonNull和nonEmpty,我想知道是否还有比if(foo.isNullOrEmpty && !bar.isNullOrEmpty)

basically this the idea is that both strings should be nonNull and nonEmpty and I was wondering if there is a more Kotlin way than doing if(foo.isNullOrEmpty && !bar.isNullOrEmpty)

推荐答案

使用此

fun <T, R, S> biLet(lhs: T, rhs: R, block: (T, R) -> S): S? = if (lhs != null && rhs != null) block(lhs, rhs) else null

用作

biLet(foo, bar) { safeFoo, safeBar ->
}

字符串的变体

fun <T: CharSequence?, S> biLet(lhs: T, rhs: T, block: (T, T) -> S): S? =
    if (lhs.isNotNullOrBlank() && rhs.isNotNullOrBlank()) block(lhs, rhs) else null

这篇关于我如何使用let检查2个条件(或应用等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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