I am new to kotlin. I am reading a key and value from properties file, in a kotlin program. But I don't know how to directly return the value of a key. Please find the application.yml and abc.class(this is a kotlin class) below.
application.yml
abcconfig:
isabcEnabled:
default: false
xyz: true
def: true
abc.class
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.stereotype.Component
@Component
@ConfigurationProperties(prefix = "abcconfig")
class AbcConfig {
private var abcEnabled: Map<String, Boolean> = mutableMapOf()
fun getabcEnabledValue(siteId: String?): Boolean {
val abc: Boolean
val key: String? = if (abcEnabled.containsKey(key)) key else "default"
abc = abcEnabled[key]
return abc
}
fun setAbcEnabled(abcEnabled: Map<String, Boolean>) {
this.abcEnabled = abcEnabled
}
}
This is about nullability. The Kotlin compiler keeps track of whether each value could be null or not, and prevents you from doing things that would be unsafe.
The code in this question has one particular nullability issue. (It also has some confusion, including two references to key
before it's set. I'll assume those should be siteId
.)
The issue is what happens when the abcEnabled
map doesn't contain the requested key. If the key is present, then the […]
operator will return the corresponding Boolean
value; but if the key is not present (which could happen if the map doesn't contain a "default" key), it returns null. However, the variable you're trying to assign it to is of type Boolean
, which doesn't allow nulls. That's why the compiler complains.
So you'll have to decide what you want to happen if the map contains no "default" key. (Or find a way to ensure it always does; but that's a lot harder, especially if the method could be called before the object is fully initialised, or while another thread is setting or updating the map. So it's much safer to handle the case gracefully.)
If you want to return false
in that case, the code could boil down to:
fun getabcEnabledValue(siteId: String?): Boolean {
val key: String? = if (abcEnabled.containsKey(siteId)) siteId else "default"
return abcEnabled[key] ?: false
}
or even (for better thread-safety as well as brevity and clarity):
fun getabcEnabledValue(siteId: String?)
= abcEnabled[siteId] ?: abcEnabled["default"] ?: false
Or if you want to return null
in that case, simply declare the function as returning Boolean?
(which allows null) — or leave off the ?: false
in the last example.
(Also, as a matter of style, I'm not sure why you've made abcEnabled
a private property and then added your own setter. Is it really necessary to hide the getter? If not, a public property would be simpler. And it's probably worth making the capitalisation of abc
in the method names consistent.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.