https://kotlinlang.org logo
s

Saiedmomen

06/10/2021, 11:41 AM
requireNotNull
does not provide smart cast null safety. Is there another way to concisely mark null as Illegal state and have smart cast?
Copy code
private var id: Long? = null

override fun delete() = runBlocking {
    requireNotNull(id)
    notesRepository.deleteNote(id!!) // id is not smart cast to not null
}
h

Hasan Hosgel (alosdev)

06/10/2021, 11:45 AM
it would work if id is a parameter of the function or you put the result of require into an value and use it
👌 1
p

Petter Måhlén

06/10/2021, 11:46 AM
notesRepository.deleteNote(requireNotNull(id))
?
👌 1
n

Nikky

06/10/2021, 11:49 AM
is id a var ?
👌 1
requireNotNull should smartcast, but it won't be able to for
var
that could change between the check and the usage
s

Saiedmomen

06/10/2021, 11:51 AM
@Nikky Oh I see
n

Nikky

06/10/2021, 11:52 AM
the id should tell you when you have a blocks like
Copy code
if(id != null) {
    notesRepository.deleteNote(id)
}
it should warn you that it cannto smartcast
id
another way to solve similar problems is to assign them to a val in that scope via
let
or similar scope functions but best would be if you can get rid of the
var
.. or change it into a parameter.. which also makes it immutable in the scope of the function
👌 1
s

Saiedmomen

06/10/2021, 11:56 AM
@Nikky Yes that makes sense. thank you
11 Views