简体   繁体   English

字符串附加Null Check Kotlin

[英]String append with Null Check Kotlin

What would be ideomic way to append String with NULL check? 用NULL检查附加String的理想方法是什么? Perhaps this is stupid question, but I am curious to know the best way. 也许这是愚蠢的问题,但我很好奇知道最好的方法。

I tried these- 我尝试过这些

fun main(args: Array<String>) {
    val foo: String? = null
    val bar = "bar"

    println("__println(\"\$foo \$bar\")")
    println("$foo $bar")

    println("__println((if (foo != null) \"\$foo \" else \"\") + (if (bar != null) \"\$bar \" else \"\"))")
    println((if (foo != null) "$foo " else "") + (if (bar != null) "$bar " else ""))

    println("__println((\"\$foo \" ?: \"\") + (\"\$bar \" ?: \"\"))")
    println(("$foo " ?: "") + ("$bar " ?: ""))

    println("__println((foo ?: \"\") + (bar ?: \"\"))")
    println((foo ?: "") + (bar ?: ""))

    println("__println(foo + \" \" + bar)")
    println(foo + " " + bar)

    var string = ""
    if (foo != null) string += "$foo, "
    if (bar != null) string += "$bar"
    println("__println(string)")
    println(string)
}

Output 输出量

 __println("$foo $bar") null bar __println((if (foo != null) "$foo " else "") + (if (bar != null) "$bar " else "")) bar __println(("$foo " ?: "") + ("$bar " ?: "")) null bar __println((foo ?: "") + (bar ?: "")) bar __println(foo + " " + bar) null bar __println(string) bar 

Purpose 目的

I have Location Data Class, in that I have address_line_1, city, state, country etc. 我有位置数据类,因为我有address_line_1,城市,州,国家等。

I want get full address string with appending all fields with null check. 我想获取完整的地址字符串,并使用null检查附加所有字段。 Please note I want append an space and comma also when value is not Null. 请注意,当value不为Null时,我还要添加一个空格和逗号。

Counterquestions: what do you want to append instead? 反问:您想附加什么? and what is your preference? 您的喜好是什么?

If I need a default value, I go with foo ?: "<default>" . 如果需要默认值,可以使用foo ?: "<default>"

If it is ok if null is printed, I just keep it as is, ie "$foo $bar" . 如果可以打印null ,那么我就保持它不变,即"$foo $bar"

If instead you just wanted to concatenate a list of strings which may or may not contain null values, you may also be interested in something like the following: 相反,如果您只是想连接可能包含或不包含null值的字符串列表,那么您可能还会对以下内容感兴趣:

listOfNotNull(foo, bar).joinToString(" ")

Now regarding your update of the question... Assuming something like the following as data class: 现在,关于您对问题的更新...假设数据类如下所示:

data class Location(val line1 : String?, val line2 : String?, val line3part1 : String?, val line3part2 : String?)

A possible usage of listOfNotNull assuming that empty lines should not be printed could like: 假设不应打印空行,则listOfNotNull的可能用法如下:

with(yourLocation) {
        // the outer listOfNotNull contains the lines:
        listOfNotNull(
            line1,
            line2,
            // inner ListOfNotNulls are specific concatenations, which may lead to an empty line (that's why takeIf is also here)
            listOfNotNull(line3part1, line3part2).takeIf { it.isNotEmpty() }
                ?.joinToString(" ")
            ).joinToString("\n")
    }.run(::println)
}

If you would require something like "($nullable)" I would go for: 如果您需要"($nullable)"我会寻求:

nullable?.let { "($it)" }

which then again can be used within the listOfNotNull . 然后可以再次在listOfNotNull使用listOfNotNull

use this logic 使用这个逻辑

var foo: String? = null
var bar = "bar"

foo?.let { foo += bar }?: run { foo="" }
println(foo)  // null not print

foo?.let { bar.let { foo += bar } }
println(foo)   //output is  bar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM