0

I have a function that receives a value as an optional value that can be null or a defined Type. So, for example a function like this:

fun myFunction(type:Type?) {}

The problem is that inside that function I call another function that requires Type to be of a Type and not null.

fun myFunction(type:Type?) {
   val conf = getConfFor(type)
}

Because of that the code won't compile. I get:

Type mismatch.
Required:
Type
Found:
Type?

I have tried to fix this by checking if the value is not null, like this:

if (type:Type !== null) val conf = getConfFor(type)

But, that didn't help. I have also tried with using let function:

val conf = type?.let { getConfFor(type) }

But, then I had problems down the chain, because other calls that used conf had also required non null value, and now conf was possible null. How can I avoid this error, by bypassing it for when the value is there, and not null, so that I avoid changing type of non null value for every function down the chain?

Leff
  • 1,968
  • 24
  • 97
  • 201
  • Ah, that is it! Thanks! – Leff Sep 15 '21 at 22:54
  • I wonder why the if approach didn’t work, because it should. Maybe because you used reference equality instead of structural equality? Honestly, !! seems a code smell to me and I try to avoid using it. – João Dias Sep 15 '21 at 23:24
  • Forcing non null `type` with `!!` will just cause your code block to crash if it's `null` which goes against entire requirement of it being an optional value. You can either assign a default `conf` for null type, keep checking if `conf` is null or just branch out to execute entirely different code for when type is null. – Pawel Sep 15 '21 at 23:50

0 Answers0