Mateusz Chrzaszcz
Mateusz Chrzaszcz

Reputation: 1280

Compiler warning while using @Value annotation in Kotlin project

Is there any type in Kotlin language that I could use in a late initialization instead of java.lang.Integer so that I do not get a compiler warning?

Let's say I have a class like this one:

class SomeClass {
 @Value(#{config['poolCapacity']?:'5000'})
 lateinit var somePool: Integer
}

I can't use Int type from Kotlin because it's primitive type and lazeint does not accept it.

If I stick to java.lang.Integer it works just fine but I am getting compiler warning of this sort:

SomeClass.kt: (20, 24): This class shouldn't be used in Kotlin. Use kotlin.Int instead.

Obviously I might create needed type myself but I simply wonder if there is something out of the box and recommended that we should use in such situation and I simply can't find it? (Annotated constructor is not a solution in this particular case).

Upvotes: 4

Views: 1205

Answers (1)

holi-java
holi-java

Reputation: 30696

The simplest solution is don't to use a late-initialized property since Kotlin late-initialized property don't support for primitive types now, and you can initialize it with the default value of spring expression, for example:

@Value(#{config['poolCapacity']?:'5000'})
var somePool: Int = 5000

A complex example you can write a delegated properties, but you must annotated at setter by @set site-target rather than field/property , for example:

@set:Value(#{config['poolCapacity']?:'5000'})
var value by required<Int>()

inline fun <reified T> required(): ReadWriteProperty<Any, T> {
    return object : ReadWriteProperty<Any, T> {
        var value: T? = null;
        override fun getValue(thisRef: Any, property: KProperty<*>): T = value as T

        override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
            this.value = value;
        }

    }
}

Upvotes: 4

Related Questions