Skip to content

Functions

View Markdown

Use ktFunction() to declare a function. Use returns {} to configure its return type, then type {} and reference() to specify that type. Use body {} for its implementation and literal() for a literal value.

import com.alexstyl.prosakt.ktFile
val source = ktFile {
ktFunction("greeting") {
returns {
type {
reference("String")
}
}
body {
literal("Hello")
}
}
}

Generated Kotlin:

fun greeting(): String {
return "Hello"
}

With an explicit non-Unit return type, Prosa.kt returns the last expression in body {} automatically.

Use parameter() inside ktFunction {} to add a parameter. Pass its name as the argument. Use type {} and reference() inside the parameter block to specify its type. Use reference() in the function body to refer to the parameter.

import com.alexstyl.prosakt.ktFile
val source = ktFile {
ktFunction("greeting") {
parameter("name") {
type {
reference("String")
}
}
returns {
type {
reference("String")
}
}
body {
reference("name")
}
}
}

Generated Kotlin:

fun greeting(name: String): String {
return name
}

Use default {} inside the parameter block to generate a default argument. Use literal() inside it for a literal value.

import com.alexstyl.prosakt.ktFile
val source = ktFile {
ktFunction("greeting") {
parameter("name") {
type {
reference("String")
}
default {
literal("World")
}
}
returns {
type {
reference("String")
}
}
body {
reference("name")
}
}
}

Generated Kotlin:

fun greeting(name: String = "World"): String {
return name
}

Call parameter() again for each additional parameter; their order is preserved. Use modifier("vararg") in a parameter block to add the vararg keyword. Constructor parameters also support type {} and default {}; see Classes.

Use call() inside body {} to generate a function call. Use argument {} to provide an argument. Omit returns {} for a function with an implicit Unit return type.

import com.alexstyl.prosakt.ktFile
val source = ktFile {
ktFunction("printGreeting") {
body {
call("println") {
argument {
literal("Hello")
}
}
}
}
}

Generated Kotlin:

fun printGreeting() {
println("Hello")
}

For a function without an implementation, set modifiers = listOf("abstract") in a valid abstract context, such as an interface.