Sourabh Rawat
06/09/2021, 5:20 PMinline 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?by
keyword, which I think is possible to be used when the variable is declared
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?raulraja
06/09/2021, 5:32 PMimport 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)
}
Sourabh Rawat
06/11/2021, 6:05 AMrequireNotNull
which would read the name of the parameter pass and create a error message accordingly.
This is my current approach
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
ephemient
06/23/2021, 9:46 PM