Search code examples
kotlinextension-methods

Are these Kotlin functions equivalent?


I've not been using Kotlin for long but I came across a code base using these patterns and I wondered if these 3 extension functions are equivalent, or is there some subtle difference in behaviour?

fun EntityObject.transform(): DtoObject {
    this.apply {
        return DtoObject(
            id = id,
            description = label
        )
    }
}
fun EntityObject.transform(): DtoObject {
    return DtoObject(
        id = id,
        description = label
    )
}
fun EntityObject.transform() = DtoObject(
        id = id,
        description = label
)

Solution

  • There is no difference in behavior.

    The first one is obtuse and over-complicated in a few different ways, from a readability standpoint. (Use of apply instead of run to create/return something else, unnecessary use of a scope function in the first place, and returning from the outer function within the scope function only so the code execution order is convoluted.)