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
spand
01/25/2019, 12:39 PM
getValue()
d
diesieben07
01/25/2019, 12:39 PM
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])
diesieben07
01/25/2019, 12:40 PM
or the above mentioned
getValue
a
Alowaniak
01/25/2019, 1:39 PM
?:
is also possible
r
rook
01/25/2019, 4:12 PM
Copy code
val s: String
someMap["foo"]?.let { s = it } ?: throw
n
Nikky
01/26/2019, 1:32 AM
the
[]
indexing operator is just calling
get
which return a Nullable because the key might not exists
you can use a fallback values with