I was playing around with reflections, reading the documentation.
Q1.
import kotlin.reflect.KFunction1
fun isOdd(x: Int) = x % 2 == 1
fun isOdd(s: String) = s == "brillig" || s == "slithy" || s == "tove"
fun main() {
val numbers = listOf(1, 2, 3)
println(numbers::class.qualifiedName)
println(numbers.filter(::isOdd)) // refers to isOdd(x: Int) among the overloaded functions, from the context
val strings = listOf("Hello", "brillig", "World", "tove")
println(strings.filter(::isOdd)) // refers to isOdd(x: String)
val n = IntRange(1, 10).toList()
println(n::class.qualifiedName)
val predicate: KFunction1<Int, Boolean> = ::isOdd
// val predicate: (Int) -> Boolean = ::isOdd // then below codes would not work
println(predicate)
println(predicate.returnType)
println(predicate.parameters)
println(predicate.parameters[0].type)
println(predicate.parameters[0].also { println(it.kind) }.name)
}
Is it correct to say that ::isOdd
actually returns the value of type KFunction1<Int, Boolean>
which is a subtype of the function type (Int) -> Boolean
?
Q2. While I was searching in the api documentation, I found out that KFunction1
, doesn’t have a page for it. Is there a reason? And in the page for KFunction
interface KFunction<out R> : KCallable<R>, Function<R>
Why does KFunction
NOT have the input parameter types in the definition, and only have the output type?
Q3. What is the difference between KFunction
and KCallable
? I’m not so sure what a callable means in Kotlin. Is it correct to say a “callable” = “function or property”, a superset of function?