Home > OS >  How to execute a Function within a When-statement?
How to execute a Function within a When-statement?

Time:09-01

I am using the following when-statement in Kotlin:

when(name) {
    "Sun" -> print("Sun is a Star")
    "Moon" -> print("Moon is a Satellite")
    "Earth" -> print("Earth is a planet")
}

And I have a function foo().

This function should be executed for every case of the when-statement.

I tried:

when(name) {
    "Sun" -> print("Sun is a Star")
    "Moon" -> print("Moon is a Satellite")
    "Earth" -> print("Earth is a planet")
    foo()
}

But I get an error.

How do I make a foo() function call within the when-statement?

CodePudding user response:

Question is if list of name is exhaustive. If it is, you can do like Alexander Ivanchenko suggests:

when(name) {
    "Sun" -> print("Sun is a Star")
    /** other code goes here */
}
foo()

Else:

when(name) {
    "Sun" -> {
        print("Sun is a Star")
        foo()
    }
    /** other code goes here */
}

CodePudding user response:

If you really want to fire foo() from when, you can define a function, let's call it fooPrint() that prints the provided message and then invokes foo():

fun fooPrint(message: String) {
    print(message)
    foo()
}

And use this function with when:

when(name) {
    "Sun" -> fooPrint("Sun is a Star")
    "Moon" -> fooPrint("Moon is a Satellite")
    "Earth" -> fooPrint("Earth is a planet")
}

Alternatively, as I've said in the comment, you can simply invoke foo() outside your when expression:

when(name) {
    "Sun" -> print("Sun is a Star")
    "Moon" -> print("Moon is a Satellite")
    "Earth" -> print("Earth is a planet")
}
foo()
  • Related