I also tried to find a generic solution for this. I ended with following code:
fun <T : Any> allNotNull(vararg elements: T?): List<T>? = if(elements.contains(null)) null else elements.filterNotNull()
I can now write something like
val firstName = parameters["firstName"]
val lastName = parameters["lastName"]
allNotNull(firstName, lastName)?.apply {
userService.add(UserDTO(firstName = this[0], lastName = this[1]))
}
The UserDTO needs String parameters, but parameters[“firstName”] is of type String? . I don’t like the syntax with this[0] much, but it is still better as chaining multiple let-calls.