0

I have bunch of data classes, with values that need to be nullable since there is possibility of database returning null for some fields.

However, when mapped to ApiClass, these values should be replaced with empty strings or certain Long values ( no nulls )

But i cant figure how to for example turn Long? to Long

in mapper i have for example

dueDilligence.info.extendedInfo.income.let { it }

which to my knowledge should only pass this value to ApiClass constructor if Long is actual long and not null, if it is null i would assume it will remain in default value given in constructos ( 0 in this case )

dueDilligence.info.extendedInfo.income is a Long that might also be null, but in case of null it should be mapped as 0.

But since data class is Long? and mapper is Long, there is type mismatch which i cant seem to solve with let or run

i can also write if( attribute == null ) { } but that will generate soooo much excess code since there is something like 50 attributes.

Clomez
  • 1,410
  • 3
  • 21
  • 41
  • 1
    Do you need Elvis operator there? Reference: https://kotlinlang.org/docs/reference/null-safety.html – user28434'mstep Jun 14 '19 at 09:55
  • I'm pretty sure the answer is `takeIf {}?.let {} ?: {}` but as you never specified a complete example for what you are trying to convert, it's hard to write an answer to it. – EpicPandaForce Jun 14 '19 at 10:45

1 Answers1

0

You can use both of the examples below, the first is to replace null values with "0" the second is to remove null values from the list:

val list = listOf<Long?>(null, 0L, 20L, 15L, 13L, 20L, null, null, 30L, 45L)
fun main(args: Array<String>){
   val listA = list.map { it ?: 0 }

   val listB = list.mapNotNull { it }

   println(listA)
   println(listB)
}

The output is:

  List A [0, 0, 20, 15, 13, 20, 0, 0, 30, 45]
  List B [0, 20, 15, 13, 20, 30, 45]
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
Edy Daoud
  • 94
  • 1
  • 5