Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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..")
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading