mgtriffid
03/17/2016, 4:55 AMlateinit
.
It's awesome that it allows not null
properties to be initialized by a framework.
But it would be great to have a way to make compiler complain if one forgets. For example, consider the following class
import com.awesome.framework.ThatFrameworkApplicationAdapter;
class MyApplicationWithSomeFramework : ThatFrameworkApplicationAdapter {
lateinit var notNullPropertyWeUse : SomeType;
@Override
fun create() {
//developer is sure that framework will call this method as part of initialization
notNullPropertyWeUse = SomeTypeFactory.getInstance().get();
}
@Override
fun doUsefulStuff() {
//some code using notNullPropertyWeUse
}
}
Okay, cool, we just mark that var
as lateinit
and that's it.
But what if this class had some significant number of such properties? Then some could be forgotten by developer.
What would be awesome is to mark some method with specific modifier or maybe annotation specifying that this method is assumed to be called by environment (framework, servlet container, whatever). And then compiler would complain if developer did not take care of some of lateinit
properties. Like "Hey, man, you say this propertyName
is lateinit
, you say that method is supposed to be called as initialization - but why you don't initialize propertyName
in that particular method?". Example:
import com.awesome.framework.ThatFrameworkApplicationAdapter;
class MyApplicationWithSomeFramework : ThatFrameworkApplicationAdapter {
lateinit var notNullPropertyWeUse : SomeType; //completely legal: this property is being initialized in create method which is marked as setup
lateinit var anotherPropertyFallenIntoPitfallOfCarelessness : OtherType; //Compile-time error: setup method doesn't init this
@Override
setup fun create() {
//developer is sure that framework will call this method as part of initialization
notNullPropertyWeUse = SomeTypeFactory.getInstance().get();
}
@Override
fun doUsefulStuff() {
//some code using notNullPropertyWeUse
}
}
Please tell, is that possible to have such even more strict check at compile time with 1.0? If not, what do you think, should I submit this to YouTrack as possible enhancement, or such feature has some huge disadvantage I don't see?