7

Is there an idiom in Kotlin for setting a variable to null if it is not already null? Something more semantically pleasing than:

var test: String? = null
if(test != null) test = null
Eliezer
  • 7,209
  • 12
  • 56
  • 103

3 Answers3

8

You can use the execute if not null idiom:

test?.let { test = null }
mfulton26
  • 29,956
  • 6
  • 64
  • 88
3

Just assign null to local variable:

test = null

In case if it's not null - you assign null to this variable. In case if variable is null - you just assign null to it, so nothing changed.

Ruslan
  • 14,229
  • 8
  • 49
  • 67
  • 1
    1) I suggest adding this as a comment to the question instead of as an answer as this doesn't actually answer the question. 2) If it is null - something does happen: an assignment. For simple properties setting it to `null` is not a problem but for properties with a backing property, etc. I can see why one might want to only set it to `null` if it isn't already `null`. – mfulton26 Sep 20 '16 at 12:09
  • But we have concrete case - defined variable, not property. – Ruslan Sep 21 '16 at 08:53
  • True. Perhaps you could clarify that if it is `null`, an assignment does happen but it just sets the variable to the same value: `null`. – mfulton26 Sep 21 '16 at 12:00
  • 1
    I know this is the better way to do it, but I was asking specifically about Kotlin idioms. – Eliezer Sep 22 '16 at 18:49
2

I came up with this extensions which makes this simpler:

inline fun <T, R> T.letThenNull(block: (T) -> R): T? { block(this); return null }
val test: Any? = null
...
test = test?.letThenNull { /* do something with test */ }
Eliezer
  • 7,209
  • 12
  • 56
  • 103