Nullability and field injection


#1

Hello,

I have a case where I inject components with guice into properties. I can’t use constructor injection as the web framework (wicket) needs to handle instantiation of the targets itself.

The code looks like this in the simplest case:

  Inject private var myService : MyService? = null

I need to set the property as nullable because the injection is done after instantiation. But now I need to use the !! operator whenever I use my service even though I know that the injection works.

I solved the !! pain with the following:

  Inject private var _myService : MyService? = null   val myService : MyService   get() = _myService!!

But the above boilerplate is a bit ugly.

I know there are some discussions about marking stuff as not null in general. But are there some elegant way of solving this that I havn’t thought of?

As a side node the following impossible code compiles but breaks at runtime:

  Inject private var _myService : MyService = null!!

(I am using the snapshot builds)

/tw


#2

One workaround could be to use a dummy implementation of MyService as the initial value


#3

Yes, I guess that is the best approach until/if there is a kotlin feature allowing overriding the non-nullability.

I will make a function creating dynamic no-op proxy and populate my pseudo-non-nullable properties.

But an annotation on the property telling the compiler to not check for nulls here would be even better. :slight_smile: