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

Antonio Aradaza

11/08/2019, 1:38 AM
Hello, how to call a function at the start of application then stop it immediately? Like "one-time" use only
a

Alowaniak

11/08/2019, 8:47 AM
Could you elaborate on that? Do you mean you want it to be impossible to call the function again? You could put whatever you want to execute at start of application in an object init and then reference that object at your application entry point (your
main
or when using spring some config bean or w/e?)
s

Stephan Schroeder

11/08/2019, 10:17 AM
yes, please elaborate. functions aren’t stopped, they just execute. Threads are stopped. So assuming you want to send a message that a program has started (and don’t care for the result or structured concurrency). you could start a coroutine that does that job:
Copy code
import kotlinx.coroutines.*
import java.util.concurrent.*
import java.net.URL

fun main() {
    GlobalScope.launch {
        URL("<http://sensei.notice.me>")
            .openStream().close()
    }
    // rest of the code
}
But if the initial action takes only a short time, why use coroutines at all. simply make it purely sequential. If you don’t want a function to be execute eleswhere you can define it within the main function.
Copy code
fun main() {
  fun senseiNoticeMe() {
        URL("<http://sensei.notice.me>")
            .openStream().close()
   } 
  senseiNoticeMe()
  // rest of the code
}
but if it’s a one-time invocation, why make it a method at all
Copy code
fun main() {
  URL("<http://sensei.notice.me>")
      .openStream().close()
  // rest of the code
}