Is there a way that a function is called and then ...
# announcements
k
Is there a way that a function is called and then not return to call site? I have a exit function which does the cleanup and logging.
d
If an exception is thrown?
k
Yes but putting the whole code under try catch is little ugly
Is there a cleaner way?
d
What are you trying to do, that makes you want to return to not the call site?
k
You can tell the typesystem you won't return by returning type
Nothing
, but I second that it's not clear what your question is.
k
@karelpeeters Basically I want to run a piece of code from anywhere and not continue the remaining code from the call site
d
I don't think methods have enough control over their callers to do that. You'll need to use standard flow control mechanisms to do that (like returning from the calling method after calling the sub-method).
k
I still don't understand what you mean.
k
In c++ I used goto at the end of the file.
😱 3
😅 2
I know the use case is pretty specific but...
d
If you were really dedicated to doing that, you might be able to achieve something similar with coroutines, but I think it would take a lot of work and not be worth it because it would probably require making most of your codebase suspendable. I'm even know if it's possible, but it's the only thing I can think of that might let you do that.
c
Yeah, what you’re looking for is essentially a goto statement, which Kotlin (or nearly any modern language) does not (and should not) support. The closest a high-level language should ever get to a goto is an exception
d
I would advise sticking to normal flow control. Oh! If you call
System.exit()
it will kill the process. You could do your logging then end the application. Based on your description of how you were using the original function this might do what you want.
👍🏻 1
c
However, if you use some kind of event bus and event-driven architecture, you could post an event in one place, and have the handler cancel the event after cleanup
👍🏻 2
k
Thanks for the suggestions
s
what about launching a coroutine and not waiting for it?