Kotlin

Comparison Between Java Static Functions and Kotlin Companion Objects

Two well-known programming languages that are utilized in the creation of numerous apps are Java and Kotlin. Kotlin provides the idea of companion objects whereas Java uses static functions, which are two alternative techniques to handle the static members. This article examines the differences and similarities between the Kotlin companion objects and Java static functions, emphasizing the unique qualities and applications of each.

Java Static Function

A Java static function, sometimes referred to as a static method, is a function that is an instance of a class rather than a member of it. Without constructing a class object, it may be invoked straight via the class title. The utility methods or actions that don’t need access to instance-specific data frequently employ static functions.

In this case, the class that is referred to as “ClassName” contains a static method named StaticMethod().

public class ClassName {
    public static void StaticMethod() {
        // body of the static method
    }
}

You may use the class title accompanied by the function name to call this static method from a different section of the code:

ClassName.StaticMethod();

Kotlin Companion Object

A companion object is a syntax feature that is used in Kotlin that enables the definition of static members inside the classes. It offers a mechanism to link the class itself, as contrasting to a definite object of the class, with certain functions or attributes. Although the companion objects can implement the interfaces and inherit from other classes, they provide greater freedom than static members.

In the following syntax, the companion object is stated inside the “ClassName” class. The StaticMethod() is a method that is declared within the companion object:

class ClassName {
    companion object {
        fun StaticMethod() {
            // body of static function
        }
    }
}

To call this static function, you can use the class name followed by the function name:

ClassName.StaticMethod()

Difference: Java Static Functions vs. Kotlin Companion Object

Both the Kotlin companion objects and Java static functions are methods to define the static members of a particular class. There are a few distinctions between the two, though:

  • The primary distinction between the Java static functions and Kotlin companion objects is the fact that the Java static functions are restricted to defining the static members inside a class and are unable to be connected directly to interfaces or other constructions. Whereas the Kotlin companion objects provide more versatility by enabling the declaration of static members that can implement the interfaces, acquire from other classes, or define the extension functions. They have access to the enclosing class’s private members as well. For easier reading, the Kotlin companion objects can be given with names. However, the word “companion” is implied and is not required.
  • The “static” keyword in a class in Java is used to declare static methods, while Kotlin allows the companion objects to be defined inside of a class using the “companion” keyword. The companion objects, on the other hand, are declared inside of classes using the “companion” keyword.
  • The Java static functions are unable to directly access the instance-specific members; they can only access the other static elements of the class. At the same time, the enclosed class’s private members are accessible to Kotlin’s companion objects.
  • The class name is used to call the static functions in Java, accompanied by the function name. In Kotlin, the companion objects are accessible via the class name and the companion object’s name. It is possible to give the companion objects with names (for example, companion object MyCompanion), although the “companion” keyword is optional and can be removed.

Example 1: Java Static Function

Let’s begin with the code example of using the Java static functions. The “Dummy” class is declared using the public access modifier, which means that it can be accessed from the other classes as well. Inside the “Dummy” class, there is a static function called “StaticJava”. The “static” keyword specifies that the function fits the class itself instead of an object of the class.

The “StaticJava” function simply prints the “Hello! Java Static Function” message to the console using the System.out.println() statement. The “main” method is defined as public and takes an array of strings (String[] args) as a parameter. Within the main function, the static function which is “StaticJava” is invoked via the class title that is tracked by the function name (Dummy.StaticJava()). This syntax allows a direct access to the static method without generating an object of the “Dummy” class.

public class Dummy {
    public static void StaticJava() {
        System.out.println("Hello! Java Static Function");
    }
    public static void main(String[] args) {
        Dummy.StaticJava();
    }
}

As soon as the code is executed on the console, the main method is called. It, in turn, calls the “StaticJava” function which results in the “Hello! Java Static Function” message being printed to the console as revealed in the following attached output image:

Example 2: Kotlin Companion Object

The companion object in Kotlin provides a way to encapsulate a related functionality in a concise and organized manner. Let’s have a simple code illustration of a Kotlin companion object to demonstrate its usage. The following attached code snippet showcases the usage of the Kotlin companion objects by defining a “Dummy” class.

Inside the “Dummy” class, there is a companion object declaration which utilizes the “companion object” keyword. The companion object acts as a holding area for the static “Dummy” class members. Inside the companion object, there is a function named “CompMethod”. This method does not receive any argument and has a unit return type.

In this situation, the method displays the “Hello! Kotlin Companion Object” string to the console using the “println” function. The “main” method is well-defined outside the “Dummy” class. Inside the “main” function, the “CompMethod” function is called using the “Dummy” class name followed by the name of the companion object and the function name (Dummy.CompMethod()). This syntax allows a direct access to the method that is declared inside the companion object.

class Dummy {
    companion object {
        fun CompMethod() {
            println("Hello! Kotlin Companion Object")
        }
    }
}
fun main() {
    Dummy.CompMethod()
}

When the code is executed, it yields a “Hello! Kotlin Companion Object” string message to the console as displayed in the following attached image:

Conclusion

The techniques for creating static members within classes are provided by both the Java static functions and Kotlin companion objects. However, the Kotlin companion objects provide more freedom by enabling the interface implementation, class inheritance, and extension function creation. This supports a clearer and more concise syntax as well as better code organization and reuse. The decision between Java static functions and Kotlin companion objects ultimately comes down to the particular needs of your project, your chosen programming approach, and the degree of functionality and flexibility that you desire.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.