https://kotlinlang.org logo
#announcements
Title
# announcements
k

kartikpatodi

07/10/2019, 4:33 PM
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

dalexander

07/10/2019, 4:34 PM
If an exception is thrown?
k

kartikpatodi

07/10/2019, 4:35 PM
Yes but putting the whole code under try catch is little ugly
Is there a cleaner way?
d

dalexander

07/10/2019, 4:37 PM
What are you trying to do, that makes you want to return to not the call site?
k

karelpeeters

07/10/2019, 4:37 PM
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

kartikpatodi

07/10/2019, 4:39 PM
@karelpeeters Basically I want to run a piece of code from anywhere and not continue the remaining code from the call site
d

dalexander

07/10/2019, 4:40 PM
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

karelpeeters

07/10/2019, 4:41 PM
I still don't understand what you mean.
k

kartikpatodi

07/10/2019, 4:41 PM
In c++ I used goto at the end of the file.
😱 3
😅 2
I know the use case is pretty specific but...
d

dalexander

07/10/2019, 4:44 PM
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

Casey Brooks

07/10/2019, 4:45 PM
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

dalexander

07/10/2019, 4:45 PM
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

Casey Brooks

07/10/2019, 4:45 PM
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

kartikpatodi

07/10/2019, 4:46 PM
Thanks for the suggestions
s

Stephan Schroeder

07/11/2019, 8:46 AM
what about launching a coroutine and not waiting for it?
5 Views