Given a java class with a setter taking a non-null...
# announcements
p
Given a java class with a setter taking a non-nullable value, and kotlin extension function with a nullable parameter, what's idiomatic way to call the setter if the param is non-null?
Copy code
fun MyPojo.init(fieldName: String? = null) {
            fieldName?.let(::setFieldName)
            fieldName?.also { setFieldName(it) }
            fieldName?.also { this.fieldName = it }
            if(fieldName != null) setFieldName(fieldName)
            if(fieldName != null) this.fieldName = fieldName
}
s
Not sure Kotlin is opinionated enough for any of them to be ideomatic. I would prefer either because of autocasting
Copy code
fieldName?.also(::setFieldName)
fieldName?.also { setFieldName(it) }
p
in the case of
fieldName?.also { setFieldName(it) }
is it not better to use the property syntax?
s
Missed that. Yes that would probably be more ideomatic
c
Personally, I find
if(fieldName != null) this.fieldName = fieldName
to be the solution that's easiest to understand at a glance. I mostly use
let
and
also
as part of longer chains as otherwise I don't always see an advantage in using them.
👍 3