Kotlin calling non final function in constructor works

前端 未结 3 837
北海茫月
北海茫月 2021-02-03 17:43

In Kotlin, it warns you when calling an abstract function in a constructor, citing the following problematic code:

abstract class Base {
    var code = calculate         


        
3条回答
  •  一生所求
    2021-02-03 18:42

    It is definitely poor practice because you are invoking calculate() on a partially constructed object. This suggests that your class has multiple phases of initialization.

    If the result of calculation() is used to initialize a member, or perform layout or something, you might consider using lazy initialization. This will defer the calculation of the result until the result is really needed.

提交回复
热议问题