kotlin

Kotlin inline function into {} brackets?


I have a function like:

private fun Logging.ILoggingEvent.populateLoggingEvent(eventId: String, data: MutableMap<String, String?> = mutableMapOf()) =
    LoggingEventData(
        eventId = eventId,
        eventName = "LoggingEvent_$eventId",
        data = data
    )

while:

data class LoggingEventData(
    val eventId: String,
    val eventName: String,
    val data: MutableMap<String, String?>,
)

and

interface ILoggingEvent {

    val timeStamp: Instant

    fun updateTimeStamp(now: Instant) {
        timeStamp = now
    }
}

Why can I not convert upper populateLoggingEvent() function into brackets:

private fun Logging.ILoggingEvent.populateLoggingEvent(eventId: String, data: MutableMap<String, String?> = mutableMapOf()) {
    LoggingEventData(
        eventId = eventId,
        eventName = "LoggingEvent_$eventId",
        data = data
    )
}

Solution

  • When a function declaration is of the form fun f() = expression, it means that f is a function that returns expression.

    To rewrite this using a block as the function body, you need to

    This means adding : LoggingEventData before the { ... }, and adding return before LoggingEventData(...).

    private fun Logging.ILoggingEvent.populateLoggingEvent(
        eventId: String, data: MutableMap<String, String?> = mutableMapOf()
    ): LoggingEventData {
        return LoggingEventData(
            eventId = eventId, 
            eventName = "LoggingEvent_$eventId", 
            data = data
        )
    }
    

    In fact, converting between expression-bodied and block-bodied functions is available as a context action in IntelliJ. Right click the expression and select "Show Context Actions" (or Cmd+Enter on macOS), and select "convert to block body".

    In your attempt, the function does not have a return type, so it becomes a Unit-returning function. The expression LoggingEventData(...) in the body is simply creating a LoggingEventData, and then discards it.

    See also the documentation.