Reputation: 3159
We're using an existing framework which - among other things - provides dependency injection through annotations. In Java, to inject field value we would do something like this:
@Inject private SomeService someService;
Since reflection allows to reassign fields that are normally final, this also a valid declaration:
@Inject private final SomeService someService = null;
To make the declaration even shorter (and also make the fields available in unit test classes, while keeping them a part of semi-private API), you could do it like this:
@Inject SomeService someService;
@Inject final SomeService someService;
When it comes to Kotlin, we're stuck with this:
@Inject private var someService: SomeService? = null
@Inject private lateinit var someService: SomeService
!!
operator) on every service use, even though we're 100% sure they will never be null - unless something went completely wrong, in which case we have bigger problems.lateinit
approach seems to perform unnecessary checks at runtime (which are, well, highly unlikely to become performance bottlenecks, but still) and is rather verbose.var
with val
without overriding getter or using a back-up field, which faces the same problem. Ironically, they are both longer than Java declarations in many cases.So - what is the preferred way of declaring annotated Kotlin fields, which will be injected automatically and we're 100% sure that they will never be null?
While I understand that there are multiple frameworks with Kotlin-friendly syntax solving similar problems (like Injekt), I'm asking if there's a nicer way of doing it with what we have.
Upvotes: 2
Views: 212
Reputation: 54725
There's a third way I use in my projects. But it's a hack.
fun <T> uninitialized(): T = null as T
@Inject private val someService: SomeService = uninitialized()
When using this approach you can use val
and Kotlin doesn't add any null
checks.
I, personally, would like Kotlin to have a legal way to achieve the same behavior, but currently there's none. Some time ago I created KT-10583 issue and described how the problem can be solved. But I'm not sure it's going to be solved in the nearest future.
Upvotes: 1