title: Property initialization using "by lazy" vs. "lateinit"
body: <p>In Kotlin, if you don't want to initialize a class property inside the constructor or in the top of the class body, you have basically these two options (from the language reference):</p>
  <ol>
  <li><a href="https://kotlinlang.org/docs/reference/delegated-properties.html#lazy" rel="noreferrer">Lazy Initialization</a></li>
  </ol>
  <blockquote>
  <p><code>lazy()</code> is a function that takes a lambda and returns an instance of <code>Lazy&lt;T&gt;</code> which can serve as a delegate for implementing a lazy property: the first call to <code>get()</code> executes the lambda passed to <code>lazy()</code> and remembers the result, subsequent calls to <code>get()</code> simply return the remembered result.</p>
  <p><strong>Example</strong></p>
  <pre><code>public class Hello {
  
     val myLazyString: String by lazy { &quot;Hello&quot; }
  
  }
  </code></pre>
  </blockquote>
  <p>So, the first call and the subsequential calls, wherever it is, to <code>myLazyString</code> will return <code>Hello</code></p>
  <ol start="2">
  <li><a href="https://kotlinlang.org/docs/reference/properties.html#late-initialized-properties" rel="noreferrer">Late Initialization</a></li>
  </ol>
  <blockquote>
  <p>Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.</p>
  <p>To handle this case, you can mark the property with the lateinit modifier:</p>
  <pre><code>public class MyTest {
     
     lateinit var subject: TestSubject
  
     @SetUp fun setup() { subject = TestSubject() }
  
     @Test fun test() { subject.method() }
  }
  </code></pre>
  <p>The modifier can only be used on var properties declared inside the body of a class (not in the primary constructor), and only when the property does not have a custom getter or setter. The type of the property must be non-null, and it must not be a primitive type.</p>
  </blockquote>
  <p>So, how to choose correctly between these two options, since both of them can solve the same problem?</p>