https://kotlinlang.org logo
#reflect
Title
# reflect
s

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(::value.name) // get the name
}

foo(someValue) -> should output "someValue"
foo(someValue2) -> should output "someValue2"
I tried with https://kotlinlang.org/docs/reflection.html#property-references but to no avail. Is this even possible?
🚫 1
I also tried delegated property. It works, but it requires the usage of
by
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")
foo.bar by del(someValue) // Not possible
Can I achieve the second scenario with delegated properties?
r

raulraja

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(self.parameters.map { it.name }) // get the name
  return value
}

fun main() {
  foo(1)
}
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?
s

Sourabh Rawat

06/11/2021, 6:05 AM
I am trying to build a custom
requireNotNull
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 ?: "${property.name} 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
e

ephemient

06/23/2021, 9:46 PM
can be done by a compiler plugin like https://github.com/bnorm/kotlin-power-assert
8 Views