Is there a “better” way to write this `create` fu...
# codingconventions
c
Is there a “better” way to write this
create
function?
Copy code
fun add(vararg s: String): String =
    s.joinToString(" ")

fun create(one: String, two: String, three: String): String {
    val m = mapOf(
        one to "one case",
        two to "two case",
        three to "three case",
        "" to ""
    )
    return add(m[one]!!, m[two]!!, m[three]!!)
}
e
Copy code
listOfNotNull(
    "one case".takeIf { one.isNotEmpty() },
    "two case".takeIf { two.isNotEmpty() },
    "three case".takeIf { three.isNotEmpty() }
).joinToString(" ")
c
Hmm, interesting… Thank you. I didn’t know about
takeIf{ }
We ended up refactoring all of this to use type-safe builders instead
m
I would prefer something like this:
Copy code
val res = sequence {
    if(one.isNotEmpty()) yield("one case")
    if(two.isNotEmpty()) yield("two case")
    if(three.isNotEmpty()) yield("three case")
}.joinToString(separator = " ")
Or using
buildList
c
Nice, thanks