寻找一种更惯用的方式在列表映射期间进行条件日志记录

Looking for a more idiomatic way to do conditional logging during a list map

在 Kotlin 中必须有一种更加 Kotlin 风格和简洁的方式来执行此操作,但我不会这样做。假设您正在执行 mapNotNull 操作。无法映射的项目将转换为 null 以被过滤掉。无法映射的项目也会导致打印警告。这段代码有效,但它真的很冗长。你能帮我trim下来吗?

    val listOfStrings = listOf("1","2","3","not an int", "4","5")

    val convertedToInts = listOfStrings.mapNotNull {
        val converted = it.toIntOrNull()
        if(converted == null){
            println("warning, cannot convert '$it' to an int")
        }
        converted
    }

我认为您的代码是惯用的且可读的。我更喜欢用明确的 null-check.

来写它

但是如果你真的想缩短 one-liner,你可以像下面那样做。但是 return null 而不是 elvis-operator:

右侧的 Unit 需要 null.apply {}
val listOfStrings = listOf("1","2","3","not an int", "4","5")

val convertedToInts: List<Int> = listOfStrings.mapNotNull {
    it.toIntOrNull() 
        ?: null.apply { println("warning, cannot convert '$it' to an int") }
}

你也可以使用 run 看起来更具可读性:

?: run { 
    println("warning, cannot convert '$it' to an int")
    null
}