How to create a static method using Kotlin?

4

In JAVA when we want to create a static method, we use static . See:

public static String getDragonGlass(){
    return String.valueOf("All the dragon glasses.");
}

And in Kotlin , what better way to represent a static method?

    
asked by anonymous 08.08.2017 / 15:27

3 answers

6

Kotlin has a slightly different mechanism. Inside a class:

companion object {
    fun getDragonGlass() : String = String.valueOf("All the dragon glasses.")
}

Call as in Java:

Classe.getDragonGlass()

There are variants of this syntax. Some people consider this syntax too verbose. Others argue that this passes the better concept and that it helps to avoid abuse of this type of method.

Documentation .

Kotlin has functions that are not methods, so it does not even have to be inside a class. But within a class to differentiate a method from a function you need to include it in a companion object.

If you want to do outside the class:

fun getDragonGlass() : String = String.valueOf("All the dragon glasses.")

It has to be inside a package. So the call will be in the context of this package. Something like this:

Pacote.getDragonGlass()
    
08.08.2017 / 15:32
4

There are no static methods in Kotlin.

It is possible to create functions at the package level level because in Kotlin, it is not necessary to have a class to have a defined function.

Something like

package acklay.pkg

fun getDragonGlass() = "All the dragon glasses";

If it is really necessary to write a function at the level of the class that does not require an instance, but, for example, it needs access to the internal members of the class whatever (an factory method is a good example). You can create the function as part of a object declaration within the class itself.

For example:

class Classe {
    private fun foo() = object {
        val dragonGlass: String = "All the dragon glasses"
    }

    fun bar() {
        val x = foo().dragonGlass
    }
}

A more similar to static, are the companion objects

class JonSnow {
    companion object {
        fun getDragonGlass(): String = "All the dragon glasses."
    }
}

The use would be like this

JonSnow.getDragonGlass()

See working on try.kotlin.

    
08.08.2017 / 15:48
0

According to the converter from java to kotlin , the corresponding code would be:

fun getDragonGlass():String {
    return ("All the dragon glasses.").toString()
}

The return type declaration is made after the function declaration:

fun getDragonGlass():String ...

To see the conversion the converter in the upper right leg.

    
08.08.2017 / 15:45