https://kotlinlang.org logo
Title
h

Hexa

11/25/2018, 12:42 PM
is there a more idiomatic way of writing this
if(!item.name.isNullOrEmpty()){
            itemMap["name"] = AttributeValue().withS(item.name)
        }
t

Tolriq

11/25/2018, 12:45 PM
Usually I do
item.name?.takeif { it.isNotEmpty() }?.let { AttributeValue().withS(it) }
h

Hexa

11/25/2018, 12:47 PM
my compiler doesnt like the
takeif
function
is that a function that I have to write or am I missing a depedency? @Tolriq
h

hallvard

11/25/2018, 12:48 PM
Personally, I find @Tolriq's solution less clear, actually. The advantage of
isNotNullOrEmpty()
is that you get more checks into one, and yet the semantics of it is very clear to the human eye.
👍 1
h

Hexa

11/25/2018, 12:49 PM
yea it seems less readable @hallvard, but I'm curious how it works
t

Tolriq

11/25/2018, 12:50 PM
it's takeIf sorry. in his case seeing that ?. is a warning it means the String can't be null so isNotEmtpy is enought. For the rest it's a matter of reading.
Depends on what you mean readable. This is a one liner that is more functional in reading. It says given a value take it if XXX then if it's not null do YYY
This is readable and functional, just needs to be used to it, but takeIf takeUnless and all those are here for that purpose.
👍 1
h

hallvard

11/25/2018, 12:52 PM
Sure, it's functional and kotlinish. I still think doing just one check is more readable in this case, but you are free to disagree, of course. And I do agree that there are plenty of other use-cases where
takeIf
is very useful.
👍 1
1
t

Tolriq

11/25/2018, 12:58 PM
Well the other advantage is that it properly handles smart cast for complex object 🙂 If item.name is mutable and could have been null then the if code would still require a !! after the item.name.
For simple case that that simple if is OK, for proper general way and Kotlin way, takeIf is a better way.
h

Hexa

11/25/2018, 1:05 PM
thanks @Tolriq
t

Tolriq

11/25/2018, 1:07 PM
Just to show the problem (your item.name can't be null but to have the idea)
class Item(var name: String? = null)

val item = Item()

fun test() {
    if (!item.name.isNullOrEmpty()) {
        var t: String = item.name
    }
}
That does not work compiler will complain that item.name is mutable and can't be smartcast 😉