Czyzby
Czyzby

Reputation: 3159

Which is the preferred syntax when using annotation-based dependency injection in Kotlin?

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

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

Answers (1)

Michael
Michael

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

Related Questions