Class with instance and class method

#1

Is it possible in Kotlin create a class that contains both, instance and class methods?
If it is possible, could you provide an example about how the code looks like?
Thanks in advance, Mariano.

#2

In Kotlin a class can only have instance methods, but it can also declare companion object.
Object methods behave like you would expect static or class methos to.
So by declaring companion object, we can call it’s methods as a static method of it’s enclosing class.

Here’s an example:

class Logger {
    val foo
    val bar

    fun baz() {
        // Example of instance method
    }

    companion object {
        fun info() {
            // Example of 'static / class' method
        }
    }

In this example, info function can be invoked as it was static / class method.

Logger.info() // static or class method

For baz, we would need to make an object of Logger class.

val lgr = Logger()
lgr.baz() // instance methos

#3

You can also declare package level functions (outside of the class). That is a very handy replacement for private static methods. You should not declare too many public package functions though.