# reflect

Sourabh Rawat

06/09/2021, 5:20 PM
I want to get the name of the actual variable passed on the call site
Copy code
inline fun <reified T> foo(value: T?): T {
    println( // get the name

foo(someValue) -> should output "someValue"
foo(someValue2) -> should output "someValue2"
I tried with but to no avail. Is this even possible?
🚫 1
I also tried delegated property. It works, but it requires the usage of
keyword, which I think is possible to be used when the variable is declared
Copy code
val someValue by del(someValue) // Possible

var foo = Foo(bar = "asd") by del(someValue) // Not possible
Can I achieve the second scenario with delegated properties?


06/09/2021, 5:32 PM
hi @Sourabh Rawat
I think this may be possible
Copy code
import kotlin.reflect.KCallable

fun <T> foo(value: T): T {
  val self : (T) -> T = ::foo
  self as KCallable<*>
  println( { }) // get the name
  return value

fun main() {
all reflected callable references extend from KCallable which if you have full reflection in the classpath you can get to the parameters of reflected callables.
I have not tested this so take with a grain of salt. 🙂
you can’t access the value named passed in though so maybe just the arg names?, what’s your use case for wanting to access the named valued passed at a call site if you don’t mind me asking?

Sourabh Rawat

06/11/2021, 6:05 AM
I am trying to build a custom
which would read the name of the parameter pass and create a error message accordingly. This is my current approach
Copy code
class RequireNotNull<T>(private val value: T?, private val message: ((KProperty<*>) -> String)?) :
    ReadOnlyProperty<Nothing?, T> {

    override fun getValue(thisRef: Nothing?, property: KProperty<*>): T {
        return requireNotNull(value) { message ?: "${} should not be null" }

    companion object {
        fun <T> requireNotNull2(
            value: T?,
            message: ((KProperty<*>) -> String)? = null
        ) = RequireNotNull(value, message)

val foo by requireNotNull2(fooBar) // gives error message based on foo
🤔 1


06/23/2021, 9:46 PM
can be done by a compiler plugin like