Home > database >  Include a lambda inside an if..else statement
Include a lambda inside an if..else statement

Time:12-09

I have the following function:

fun ValueListItem(
    label: String,
    value: String,
    onClick: (() -> Unit)? = null
) {

}

But calling it like this is not allowed:

var edited = false

ValueListItem(
    label = "my label",
    value = "some value",
    onClick = if (viewmodel.canEdit) { edited = true } else null
)

But calling it like this is allowed:

var edited = false

val onEditDateTime = {
  edited = true
}

ValueListItem(
    label = "my label",
    value = "some value",
    onClick = if (viewmodel.canEdit) onEditDateTime else null
)

How can I pass the lambda in a conditional statement rather than having to declare the lambda as an extra construct.

CodePudding user response:

By writing

ValueListItem(
    label = "my label",
    value = "some value",
    onClick = if (viewmodel.canEdit) { edited = true } else null
)

The compiler sees the braces as part of the if-statement syntax. Simply adding another pair of braces like this should do the trick I think

ValueListItem(
    label = "my label",
    value = "some value",
    onClick = if (viewmodel.canEdit) {{ edited = true }} else null
)
  • Related