is there a more idiomatic way of writing this ``` ...
# announcements
h
is there a more idiomatic way of writing this
Copy code
if(!item.name.isNullOrEmpty()){
            itemMap["name"] = AttributeValue().withS(item.name)
        }
t
Usually I do
Copy code
item.name?.takeif { it.isNotEmpty() }?.let { AttributeValue().withS(it) }
h
Screen Shot 2018-11-25 at 12.46.14.png
my compiler doesnt like the
takeif
function
is that a function that I have to write or am I missing a depedency? @Tolriq
h
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
yea it seems less readable @hallvard, but I'm curious how it works
t
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
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
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
thanks @Tolriq
t
Just to show the problem (your item.name can't be null but to have the idea)
Copy code
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 😉