I have this map: private val listOfFeeds : Map&lt...
# getting-started
f
I have this map: private val listOfFeeds : Map<String, String> If I try to access an element with val s = listOfFeeds[key] The return type of "s" is String? And not String. I guess that's because the compiler can't assume it'll get a value for that key. Right? And if so, how can I work around the problem? Is !! the only solution here?
s
getValue()
d
Do a null check:
Copy code
val s = listOfFeeds[key]
if (s == null) {
  // code for null
} else {
  // code for non-null
}
Alternatively you can use
map.getOrDefault(key, defaultValue)
. Or, if you are really sure that it's not null you can use
!!
or
checkNotNull(map[key])
or the above mentioned
getValue
a
?:
is also possible
r
Copy code
val s: String
someMap["foo"]?.let { s = it } ?: throw
n
the
[]
indexing operator is just calling
get
which return a Nullable because the key might not exists you can use a fallback values with
?:
or throw in that case i like to use
?.let { doSomethingWith(it)}
personally andyou could also just use
!!
to null assert