junk
junk

Reputation: 987

Can kotlin define dynamic method when class init?

My class:

class Demo {
    init {
        // define method here my some array:[a,b,c]
        // such as fun Demo.a,Demo.b...
    }
}

Function names are dynamic.

Can Kotlin do this?

Upvotes: 4

Views: 2453

Answers (2)

Kirill Rakhman
Kirill Rakhman

Reputation: 43811

No, you can't dynamically define functions in classes, but because functions are also objects, you can dynamically store them (in a field, array, map) and call them dynamically. Using some language features of Kotlin we can get a quite terse syntax:

class Demo(name: String) {
    private val functions: Map<String, () -> Any> = mapOf(name to { "Hello $name" })

    operator fun get(name: String): Any? = functions[name]?.invoke()
}

fun main(args: Array<String>) {
    val demo = Demo("Kirill")

    println(demo["Kirill"])
}

Output:

Hello Kirill

Upvotes: 5

nhaarman
nhaarman

Reputation: 100378

No, Kotlin is a statically typed language. That means that the type every variable and method must be known at compile-time.

Upvotes: 2

Related Questions