My parent variable is nullable, and haves a getWidth function. I wanna call getWidth only if parent is not null, so i did this let function.
return parent.let {
it.getWidth() * (perWidth / 100.0f)
} ?: run{
App.realWidth.toFloat()
}
Also, if is null, I wanna call App.realWidth.toFloat(), so I added it in a ?: run which I read is like doing an else in a let function.
The problem is that it is giving me this error on it.getWidth()
Only safe (?.) or non-null asserted (!!.) calls are allowed on a
nullable receiver of type ParentInterface?
I don’t understand why, because it can’t be null, as it is inside a let block.
Can someone explain me how to solve this?
Thanks
>Solution :
You should write it as
return parent?.let {
Otherwise it still comes in the let block when it’s null, with it being null