Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
简化Kotlin中多个嵌套块的返回_Kotlin - Fatal编程技术网

简化Kotlin中多个嵌套块的返回

简化Kotlin中多个嵌套块的返回,kotlin,Kotlin,有关守则如下: fun get(context: Context, s: String): MyObjectDb? { return context.database.use { return@use select(MyObjectDb.TABLE_NAME, *MyObjectDb.PROJECTION) .whereArgs("${MyObjectDb.COLUMN_S} = {s}", "s" to s)

有关守则如下:

fun get(context: Context, s: String): MyObjectDb? {
    return context.database.use {
        return@use select(MyObjectDb.TABLE_NAME, *MyObjectDb.PROJECTION)
                    .whereArgs("${MyObjectDb.COLUMN_S} = {s}", "s" to s)
                        .exec {
                            return@exec getOne(MyObjectDb::fromCursor)
                        }
    }
}
当我检查代码样式(sonar with Kotlin插件使用detekt)时,我得到一个警告,我应该“限制方法中返回语句的数量”


有没有办法只回来return@exec或者以更加Kotlinization的方式编写代码-没有那么多返回。

当lambda只包含一个表达式时,可以省略
return
。由于函数也只包含一个表达式,因此可以在
=
之后编写函数体,以省略此处的返回。因此,您可以将代码缩短为:

fun get(context: Context, s: String): MyObjectDb? = context.database.use {
    select(MyObjectDb.TABLE_NAME, *MyObjectDb.PROJECTION)
        .whereArgs("${MyObjectDb.COLUMN_S} = {s}", "s" to s)
        .exec { getOne(MyObjectDb::fromCursor) }
}

当lambda仅包含一个表达式时,可以省略
return
。由于函数也只包含一个表达式,因此可以在
=
之后编写函数体,以省略此处的返回。因此,您可以将代码缩短为:

fun get(context: Context, s: String): MyObjectDb? = context.database.use {
    select(MyObjectDb.TABLE_NAME, *MyObjectDb.PROJECTION)
        .whereArgs("${MyObjectDb.COLUMN_S} = {s}", "s" to s)
        .exec { getOne(MyObjectDb::fromCursor) }
}