Hi All, I’m new to kotlin and facing 1 issue while...
# getting-started
r
Hi All, I’m new to kotlin and facing 1 issue while using a config property for boolean in my class. I couldnt pass it as a constructor argument as there are already 6 parameters and detekt wont allow me to do so:
Copy code
@ConfigProperty(name = "event-enabled")
lateinit var eventEnabled: Boolean
For all the other types like String I’m able to do it. But for Boolean it fails with the error “‘lateinit’ modifier is not allowed on properties of primitive types”. I tried by removing lateinit, and it is giving me initialization errors. Can someone please help me on this?
e
lateinit
doesn't work for primitives or nullables. it's basically a nullable field under the covers, with a null check on every read. you can replace it with
Copy code
var eventEnabled: Boolean = false
if you don't need to be guarded against read-before-initialization,
Copy code
var eventEnabled: Boolean by Delegates.notNull()
if you do, or
Copy code
var eventEnabled: Boolean? = null
with a
eventEnabled!!
check on read, for less overhead than delegates
r
I tried both var eventEnabled: Boolean = false and var eventEnabled: Boolean? = null the error says Injected field should not be initialized
e
ah it's magic framework stuff… don't think you have a way around that
r
yeah using this inside @ApplicationScoped class
k
Is this a data class? If so, I think Detekt has a setting to ignore long parameter lists in data classes.
m
Or you can just suppress it for this case where you know it is not recommended but it is better than alternatives. Making something mutable and lateinit to just shrink the size of a constructor arg list is wrong. The goal of the warning is to reduce what the class is doing or try to group properties together into their own class.
plus1 2
k
There are ways a long list of properties can be reduced. For example, if you have many Boolean properties, they can often be grouped into a single property
val flags: EnumSet<FooBarOptions>
r
Yeah, I can change the setting in detekt yml, but before I do that wanted to check if some alternative is possible
Its not a data class, its a regular class
e
if constructor is an option, I'd just suppress on that class
constructor injection is better than lateinit, enough to override the parameter count guidance, IMO.
r
Yeah, seems thats the easy and better way
thanks all