Home > database >  Kotlin: Can I assign a function to a variable in a companion object from main?
Kotlin: Can I assign a function to a variable in a companion object from main?

Time:11-30

New to kotlin, wondering if it's possible to dynamically assign a function to a companion object's variable. Read the docs and some answers here but there's no mentioning about this.

class Printer {
    companion object {
        fun printAnything() {
            println("printing anything..")
        }
    }
}

fun printA() {
    println("printing A!")
}

fun main(args: Array<String>) {
    printA()
    Printer.printAnything = :: printA // doesn't compile, perhaps a different way?
}

CodePudding user response:

You can't reassign a function that was declared with fun. It will always point to the same function. But you can make a var that holds a reference to a function. A var or val property holding a function can be invoked as a function, the same as if it was a fun declaration.

fun defaultPrintAnything() {
    println("printing anything...")
}

var printAnything = ::defaultPrintAnything

fun printA() {
    println("printing A!")
}

fun main() {
    printAnything() // calls defaultPrintAnything
    printAnything = ::printA
    printAnything() // calls printA
}

You can make a variable like this anywhere you like, whether it's in a companion object or not. So yes, you can make your Printer companion object this way:

class Printer {
    companion object {
        var printAnything = {
            println("printing anything..")
        }
    }
}
  • Related