mardi 1 décembre 2020

How to get variable name from an object in Kotlin?

I have a function:

internal fun <T> List<T>.shouldBeNotEmpty(): ListAssert<T> = 
    Assertions.assertThat(this).withFailMessage("List should not be empty but is ${this::class.simpleName}!").isNotEmpty

and I am using it like:

val dataList: List<Data> = data.doSomething()

assertAll{
    ...
    dataList.shouldNotBeEmpty()
    ...
}

Now I have this message:

("List ${this::class.simpleName} should not be empty!")

but it (of course) showing in the terminal like this:

List ArrayList should not be empty!

but I would like to have it like:

List dataList should not be empty!

Can I somehow take the variable name out of an existing object using reflection or anything else?





Aucun commentaire:

Enregistrer un commentaire