1

Kotlin has quite a lot of goodies, so I was wondering, if it has the feature, which I have last seen when working with C/C++ macros:

I would like to be able to get the expression passed to a parameter of a called function. This would mostly be used for validation / logging purposes. E.g.:

fun checkNotNull(val value: Any?) {
    if (value == null)
        throw IllegalArgumentException("${value::passedExpression} is null")
}

val foo = Person(name = "Ada", surname = null)

checkNotNull(foo.surname)

So this would throw "foo.surname is null". This would save quite a lot of writing, which seems to be Kotlin's mission (or one of). It may have limitations, e.g. only return the expression if it's simple, like object graph navigation, null otherwise.

Is there any such feature? Or a feature request? Or perhaps pre-compiler addon?

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
  • You can try to use reflection or delegates as stated in [this question](https://stackoverflow.com/questions/53188226/how-to-get-the-name-of-a-variable-in-kotlin), but I have just tried reflection and received the message *references to variables aren't supported yet* on Kotlin playground, may be true... Couldn't check it out in an IDE. – deHaar Dec 18 '19 at 09:44

0 Answers0