Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String append with Null Check Kotlin

Tags:

kotlin

What would be ideomic way to append String with NULL check? 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.

I want get full address string with appending all fields with null check. Please note I want append an space and comma also when value is not Null.

like image 466
Khemraj Sharma Avatar asked Oct 26 '18 10:10

Khemraj Sharma


2 Answers

Counterquestions: what do you want to append instead? and what is your preference?

If I need a default value, I go with foo ?: "<default>".

If it is ok if null is printed, I just keep it as is, i.e. "$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:

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:

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?.let { "($it)" }

which then again can be used within the listOfNotNull.

like image 94
Roland Avatar answered Sep 22 '22 14:09

Roland


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
like image 21
sasikumar Avatar answered Sep 22 '22 14:09

sasikumar