Lifecycle methods in statically typed languages
<p>In the last year I've become a mobile developer and a functional programming admirer.</p>

<p>In each of the mobile arenas there are components with lifecycle methods that make up the meat of the app. The following will use Android and Kotlin as examples, but the same applies to iOS and Swift.</p>

<p>In Android, there are <code>Activity</code>'s with lifecycle methods like <code>onCreate()</code>. You might also define a function, <code>onButtonClicked()</code>, which will do exactly what the name describes.</p>

<p>For the purposes of the question, let's say there's a variable defined in <code>onCreate()</code> that is used in a button click handler <code>onButtonClickedPrintMessageLength()</code> (<em>This is usually the case - <code>onCreate()</code> is essentially <code>Activity</code>'s setup method</em>).</p>

<p>The example class would look like this:</p>

<pre><code>class ExampleActivity: Activity() {
    var savedStateMessage: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        savedStateMessage = "Hello World!"
    }

    fun onButtonClickedPrintMessageLength() {
        System.out.println(savedStateMessage?.length)
    }
}
</code></pre>

<p>Notice the declaration of <code>savedStateMessage</code> as a <code>String?</code> (nullable string) and the use of <code>?.</code> (null safe call). These are required because the compiler cant guarantee that <code>onCreate()</code> will be called before <code>onButtonClickedPrintMessageLength()</code>. As developers though, <a href="https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle" rel="nofollow">we know that <code>onCreate</code> will always be called first</a><strong>*</strong> <strong>**</strong>.</p>

<p>My question is <strong>how can I tell the compiler about the guaranteed order of these methods and eliminate the null checking behavior?</strong> </p>

<p>* I suppose it's possible to <code>new</code> up our <code>ExampleActivity</code> and call <code>onButtonClickedPrintMessageLength()</code> directly, thus sidestepping the Android framework and lifecycle methods, but the compiler/JVM would likely run into an error before anything interesting happened.</p>

<p>** The guarantee that <code>onCreate</code> is called first is provided by the Android framework, which is an external source of truth and might break/function differently in the future. Seeing that all Android apps are based on this source of truth though, I believe it's safe to trust.</p>