Alex
Alex

Reputation: 53

Kotlin multiple variables Null checker method implementation

I have multiple variables that can be nullable and i need to check them ( Strings and Dates ) .

I need a method where i pass it X number of variables and it returns me a list of the variables that are null.

I was thinking something that i can call like this :

internal fun checkNullVariables ( var x, var y , ..... ) : MutableList<String>{

    // yada yada

    return listOfNamesOfNullVariables
}

Upvotes: 0

Views: 874

Answers (3)

Roland
Roland

Reputation: 23232

I still recommend the Map-approach. You may want to use properties stored in a map to overcome the use of reflection.

Here is an example using a type with 2 dates and 2 strings, both having a nullable and a non-null variant:

class YourData(internal val backedMap : Map<String, Any?>) {
  val beginDate : Date by backedMap
  val endDate : Date? by backedMap
  val maybeString : String? by backedMap
  val string : String by backedMap
  constructor(beginDate : Date, string : String, endDate: Date? = null, maybeString : String? = null) : this(mapOf(
      "beginDate" to beginDate,
      "endDate" to endDate,
      "maybeString" to maybeString,
      "string" to string
  ))
}

While it may seem more complicated having that additional constructor in place, it just helps to easily create new objects the way you are most comfortable with.

Now you can either supply that function I placed in the comment or any variant of it. I now use an extension function for YourData instead:

fun YourData.getKeysWithNullValues() = backedMap.filterValues { it == null }.keys

Usage then may look as follows:

YourData(Date(), "test string")
  .getKeysWithNullValues()
  .forEach(::println)

which for this example would print:

endDate
maybeString

Upvotes: 0

Tenfour04
Tenfour04

Reputation: 93531

This definitely requires reflection, since you want parameter names. You need to add reflection as a dependency as explained in the documentation to use the below code.

private fun listNullProperties (vararg props: KProperty0<Any?>) : List<String> {
    val list = mutableListOf<String>()
    for (prop in props)
        if (param.get() == null)
            list.add(param.name)
    return list
}

Usage:

val nullPropertiesByName = listNullParameters(
    ::myProperty,
    ::myOtherProperty,
    ::myDateProperty
)
println(nullPropertiesByName.joinToString())

Upvotes: 1

sschrass
sschrass

Reputation: 7156

If it is just about logging, you could:

fun <T> T?.logNull(name: String) {
    when(this) {
        null -> //log '$name' was null
        else -> //do nothing
    }
}

and call it like

var a: String? = null
a.logNull("my a variable") // "'my a variable' was null"

Upvotes: 0

Related Questions