Hi, I am trying to give a value to a entity (creat...
# getting-started
d
Hi, I am trying to give a value to a entity (createEmail) based on entering enum type. Unfortunately, the value in the block is Unit type instead of CreateEmail. How to solve it? ( Method createErrorEmail is returning CreateEmail)
Copy code
val createEmail = {
            if (type == Type.ERROR) {
                dataProvider.createErrorEmail(id)
            }
        }
n
Try using a
when
statement.
Copy code
val createEmail = when (type) {
  Type.ERROR -> dataProvider.createErrorEmail(id)
}
https://kotlinlang.org/docs/control-flow.html#when-expression
r
Surrounding arbitrary code with braces in Kotlin does not create a block, it creates a lambda. What you're code is actually returning is
() -> Unit
, not
Unit
.
💯 1
If you are trying to have a
() -> CreateEmail
, you need to provide an else branch:
Copy code
val createEmail = {
    if (type == Type.ERROR) {
        dataProvider.createErrorEmail(id)
    } else {
        // some other CreateEmail
    }
}
or use a when statement similar to what @Nolan suggested, but wrapped in braces:
Copy code
val createEmail = {
    when (type) {
        Type.ERROR -> dataProvider.createErrorEmail(id)
        // Other branches
    }
}
You can also specify the type explicitly to get a compiler error and avoid type inference altogether:
Copy code
val createEmail: () -> CreateEmail = ...
1
s
@Dipendra Singh so to make it short (combining the remarks from earlier): drop the curly brackets and add an else-case.