CodeBlanks Logo Icon CodeBlanks

KFunction

Learn method info with KFunction.

Function info with KFunction

KFunction holds a reference to a function. It is obtained with ::functionName. name gives the function name; parameters gives the parameter list.

Example: fun greet(name: String): String = "Hello, $name!". val fn = ::greet. fn.name returns "greet". fn.parameters.size gives 1. This pattern inspects function metadata.

parameters and returnType

KFunction.parameters returns a list of parameters; each has a name and type. returnType gives the function's return type.

Example: fun add(a: Int, b: Int): Int = a + b. ::add.parameters.size returns 2. ::add.returnType gives the Int type. This info is used to process function signatures dynamically.

Practice Print the greet function name

Define fun greet(name: String): String that returns "Hello, $name!". In main take the reference val fn = ::greet and call println(fn.name).

Starter code

Main.kt
// greet function: returns Hello, {name}!
// in main take fn reference, print its name

Sample solution

Main.kt
fun greet(name: String): String {
    return "Hello, $name!"
}

fun main() {
    val fn = ::greet
    println(fn.name)
}

Expected output

greet

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the KFunction parts

Term Meaning
::greet Function reference
fn.name Function name
fn.parameters Parameters
fn.returnType Return type

2 What does KFunction's name property return?

  • Parameter count
  • Function name Correct answer
  • Return type
  • Call result

Explanation: name gives the function name.

3 Complete the KFunction reference

Question
fun greet(name: String): String = "Hello, $name!"
val fn = ____
Answer
fun greet(name: String): String = "Hello, $name!"
val fn = ::greet

Explanation: ::greet gives a KFunction reference.

All lessons in Advanced