https://kotlinlang.org logo
Title
p

Paul N

08/22/2019, 8:53 AM
If I want to get something out of an http session, it can be either null, or of a particular type, which I have to cast to. So to cope with this I've coded something like this:
val tokenMap = (session.getAttribute(sessionAttributeName)   ?: mutableMapOf<String, AgedToken>()) as MutableMap<String, AgedToken>
Which means I do get a compiler warning "Warning:(39, 55) Kotlin: Unchecked cast: Any to MutableMap<String, AgedToken>" Is there any way I can do this better and get rid of the warning ?
s

spand

08/22/2019, 9:02 AM
What is your particular issue ? The warning or the fact that you do an unsafe action ?
p

Paul N

08/22/2019, 9:17 AM
My issue is that an HttpSession is a big box of anything in effect. I have to check for nulls, I have to do a cast. I get a warning as a result of the cast. The issue is, do I have to worry about the warning or not ? If I do, is there a better way to write my code that eliminates the warning ?
k

karelpeeters

08/22/2019, 9:21 AM
The unchecked cast warnings means that the runtime can't actually check that cast. If it ever turns out that the map you're casting has differently typed values the code won't immediately crash and you'll get errors much later in the program when you actually try to get vales out of the map. So it's not a problem per se but you need to be absolutely sure something like that can never happen.
👍 1
s

spand

08/22/2019, 9:22 AM
Its difficult because you both have a session in which anything can be placed, and a mutablemap. If you really care then you can create your own type instead of the mutable map that enforces the <String, AgedToken> thing. You still need to cast it when you retrieve it from the session but if you dont use generics it will result in an exception if mismatched unlike the unchecked cast.
👍 1
p

Paul N

08/22/2019, 9:48 AM
Thanks - I'll give it a go.