Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject primitive variables in Kotlin?

I am using Dagger2 for DI in my Android app, and using this code for injecting classes into my Activity is fine:

@field:[Inject ApplicationContext]
lateinit var context: Context

but, lateinit modifier is not allowed on primitive type properties in Kotlin (for instance Boolean), how can I do something like this?

@field:[Inject Named("isDemo")]
lateinit var isDemo: Boolean

when I remove lateinit from this code I get this error Dagger does not support injection into private fields

like image 867
Mohsen Mirhoseini Avatar asked Jun 23 '17 09:06

Mohsen Mirhoseini


People also ask

What does @inject mean in Kotlin?

@Inject is a Java annotation for describing the dependencies of a class that is part of Java EE (now called Jakarta EE). It is part of CDI (Contexts and Dependency Injection) which is a standard dependency injection framework included in Java EE 6 and higher.

How do you set a variable in Kotlin?

Kotlin uses two different keywords to declare variables: val and var . Use val for a variable whose value never changes. You can't reassign a value to a variable that was declared using val . Use var for a variable whose value can change.

Does Kotlin allow primitive data types?

Kotlin doesn't have primitive type (I mean you cannot declare primitive directly). It uses classes like Int , Float as an object wrapper for primitives. When kotlin code is converted to jvm code, whenever possible, "primitive object" is converted to java primitive.


1 Answers

First, you don't need lateinit, you can leave it as a var, and initialize with an arbitrary value. Second, you must expose a field in order to allow Dagger to inject there. So, here's the solution:

@JvmField // expose a field
@field:[Inject Named("isDemo")] // leave your annotatios unchanged
var isDemo: Boolean = false // set a default value
like image 180
Miha_x64 Avatar answered Oct 18 '22 06:10

Miha_x64