# İs there a way to create an extension function for Any that returns that variables name?

**URL:** <https://discuss.kotlinlang.org/t/is-there-a-way-to-create-an-extension-function-for-any-that-returns-that-variables-name/24438>\
**Category:** Support\
**Created:** [March 17, 2022, 1:15pm UTC](https://discuss.kotlinlang.org/t/is-there-a-way-to-create-an-extension-function-for-any-that-returns-that-variables-name/24438 "2022-03-17T13:15:08Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ProtoTurquie](https://avatars.discourse-cdn.com/v4/letter/p/c5a1d2/32.png) [@ProtoTurquie](https://discuss.kotlinlang.org/u/ProtoTurquie)\
**Post date:** [March 17, 2022, 1:15pm UTC](https://discuss.kotlinlang.org/t/is-there-a-way-to-create-an-extension-function-for-any-that-returns-that-variables-name/24438/1 "2022-03-17T13:15:08Z")

</div>

Basically, i need something like this

```auto
fun Any.GetVariableNameAndValue() : String
{
    return "${this.reflection.name}: ${this}" // something like this
}

```

if the variable is directly passed without declaring it as a variable, the name should be null i guess? is there a way to do this?

---

<div class="post-metadata">

**Author:** ![kyay10](https://avatars.discourse-cdn.com/v4/letter/k/c57346/32.png) [@kyay10](https://discuss.kotlinlang.org/u/kyay10)\
**Post date:** [March 17, 2022, 5:06pm UTC](https://discuss.kotlinlang.org/t/is-there-a-way-to-create-an-extension-function-for-any-that-returns-that-variables-name/24438/2 "2022-03-17T17:06:44Z")

</div>

You can have it operate on a reference instead:

```run-kotlin
import kotlin.reflect.*

class Foo {
   val foo = "hello"
}

var bar = 42

fun main() {
    val baz = "world"
    println(Foo()::foo.variableNameAndValue)
    println(::bar.variableNameAndValue)
    //println(::baz.variableNameAndValue) sadly doesn't work for local variables :(
}

val KProperty0<*>.variableNameAndValue get() = "$name: ${get()}"
```
