Home > OS >  What is the Idiomatic way to create object in Kotlin if attribute is not empty nor null
What is the Idiomatic way to create object in Kotlin if attribute is not empty nor null

Time:04-10

what is the idiomatic way to write this code in Kotlin?

  fun createAnswerValue(record: Record):  QuestionnaireResponseItemComponent{
    val list = createAnswerList(record)
    if (list.isNotEmpty()) {
        return QuestionnaireResponseItemComponent().apply {
            linkId = record.siblingIndexUID
            answer = list
        }
    }
    return null

}

CodePudding user response:

It could be a one-liner.

UPDATE: As @Tenfour04 mentioned in comments, it would be more performant to check list for non-nullability first:

fun createAnswerValue(): QuestionnaireResponseItemComponent? =
    createAnswerList(record)
        ?.takeIf { it.isNotEmpty() }
        ?.let {
            QuestionnaireResponseItemComponent(
                linkId = record.siblingIndexUID,
                answer = it
            )
        }

CodePudding user response:

Personally I'd do this:

fun createAnswerValue(record: Record): QuestionnaireResponseItemComponent? {
    val list = createAnswerList(record)
    return if (list.isNotEmpty()) QuestionnaireResponseItemComponent().apply {
        linkId = record.siblingIndexUID
        answer = list
    } else null
}

which is pretty much what you already had, just using else and with the return lifted out as a result. It's simple and readable!

If you want to use takeIf like in @Михаил's answer, I'd probably do it this way:

fun createAnswerValue(): QuestionnaireResponseItemComponent? =
    createAnswerList(record)
        .takeIf { it.isNotEmpty }
        ?.let { list ->
            QuestionnaireResponseItemComponent().apply {
                linkId = record.siblingIndexUID
                answer = list
            }
        }

the difference being that in this one, the object is only created if it's going to be returned - if you don't care then Михаил's version is obviously more compact!

But this more Kotliny version does the same as the if/else one I posted - I'd argue that version is more readable than this (it's not too bad though). Chaining a bunch of calls together can make things nice and readable and elegant, but it can also overcomplicate things and make it hard to understand exactly what's going on. And I've definitely written my fair share of that! So I feel like "idiomatic" code is something to be careful about - knowing your options is good! But go with what works, don't feel like you need to use a language feature because it's there IMO

  • Related