Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

How to create static methods and classes in Kotlin

how to create a static method in kotlin

One of the key differences between the object-oriented model in Kotlin and Java is the definition of static methods and classes. Generally speaking, a static class doesn’t have to be instantiated in order to be used. Similarly, to invoke a static method, we just have to know its name, not to instantiate an object of the class where such a method is defined.

Kotlin Logo Over Colorful Swirl

In Java, classes may easily declare static fields or methods. However, the definition of a static class is a bit more complex. Kotlin, on the other hand, greatly simplifies the job with native constructs such as package-level functions, object s, and companion object s.

In this article, we are first going to look at the legacy Java way of declaring static classes and methods. Secondly, we’ll see how the same thing can be achieved, with much less effort, in Kotlin. Then, we’ll compare the benefits of Kotlin’s way with respect to code reusability.

Table of contents:

Static classes and methods in Java

Static classes in kotlin, package-level functions, companion objects, a comparison.

In object-oriented programming (OOP), static methods and fields are useful to model common values or operations that do not need to be tied to an instance of a class. For example, the Math class contains several static fields and methods for common constants (such as pi) and mathematical operations (such as max and min):

Static classes, on the other hand, are more tricky to define. In Java, only nested classes (that is, classes defined within another class) can be declared static. They do not need a reference to the outer class (the class they’re declared within). Hence, while we may not instantiate non-static nested classes without an instance of the outer class, static classes are independent.

Furthermore, the class loader loads the code of static classes when they are first used and not when the enclosing class gets loaded. This allows us to reduce the memory footprint of our application.

For example, we may want to use static classes to implement a thread-safe singleton class without paying the price of synchronizing the getInstance method:

In the example above, using a static class to hold a reference to the singleton instance gives us some nice properties:

  • the class-loader only loads SingletonHolder the first time it’s accessed (via Singleton::getInstance() );
  • when a Java class is loaded, it is guaranteed that all of its static properties are initialized. Hence, SingletonHolder::INSTANCE gets instantiated immediately before the first usage;
  • SingletonHolder::INSTANCE can be declared final even though it’s lazily initialized;
  • the class-loader itself is thread-safe, which makes the first two properties thread-safe

Besides performance reasons, static classes are often used to improve the readability and the maintainability of the code, as we can use them to move components closer to where they are used.

As Java, Kotlin allows us to define nested classes in our code. In Kotlin, however, a nested class is static by default. That is, by default nested classes in Kotlin do not hold a reference to the enclosing class:

In the example above, we defined a nested class Engine inside a class Car . As we can see, we can instantiate Car and Engine separately. In particular, we create an instance of Engine without providing a reference to an object of Car . The only clue that Engine is defined inside Car is its qualified name, Car.Engine . The example above prints Gasoline and SomeModel .

Static classes in Kotlin can access the properties of the companion object of the enclosing class. We’ll see more about companion object s below.

If we want to define a nonstatic nested class in Kotlin we have to declare it as inner :

Now that Engine is marked as inner , we have to create an instance of Car and use it to instantiate Engine . From within Engine , we can reference the outer object using this@Car . The example prints SomeModel - Gasoline .

Similar to Java, nested classes can be declared also in the scope of a method of the enclosing class. In this case, the new class would be a local type.

how to create a static method in kotlin

Over 200k developers use LogRocket to create better digital experiences

how to create a static method in kotlin

The main benefit of Kotlin’s approach is that it limits the risks of memory leaks, by default. In Java, it is easier to overlook the fact that a given nested class holds a reference to the enclosing class. In Kotlin, on the other hand, such a reference does not exist by default.

Whether to use an inner class or a static one largely depends on the way we’re modeling our domain. Surely, static classes allow for greater code reusability, as we do not need to instantiate the enclosing class, while letting us define (possibly) dependent components close to one another.

Static methods in Kotlin

Kotlin greatly simplifies how we can define static methods or variables. In particular, it does so using (companion) object s and package-level functions.

Kotlin is not exclusively an object-oriented language because it also supports the functional programming paradigm: this is where package-level functions come from. As the name suggests, they are functions (or members) that do not belong to a given class but are instead defined within a package. Often, they are utility functions that are independent of any other class.

For example, we can use them to implement handy functions to initialize a class. Assume we have a class named Point to model a point in the Cartesian plane:

Then, in a different package, we might define the following functions:

We can then use the functions and values above just by importing them:

The main function above prints the strings Point(0, 0) and Point(5, 0) .

Note how we defined two package-level functions in the com.logrocket.blog.utils package, onXAxis and onYAxis . We also defined a package-level value, centerPoint . Both the functions and the value can be accessed without any references to any enclosing classes, as we’d have done in Java: we just have to import them.

Package-level functions and values are syntactic sugar for static fields and methods in Java. What the Kotlin compiler does is generate a Java class named after the Kotlin file, with static methods and fields in it. For example, the functions in com.logrocket.blog.utils.factory.kt will be compiled into a class named com.logrocket.blog.utils.FactoryKt (where the name of the class is built using the name of the file and Kt, in PascalCase):

If we wanted to change the name of the generated Java class, we could use the @JvmName annotation. For example, if we place the annotation @file:JvmName("PointFactory") at the beginning of factory.kt , the generated class will be named PointFactoryKt instead of FactoryKt . Such an annotation must appear before the package directive.

Lastly, if we want more utility functions to be compiled into the same generated Java class, or if we already have a file named pointfactory.kt , we can use the @JvmMultifileClass annotation. This way, the compiler will generate a Java façade class with the specified name and all the declarations from all the Kotlin files with the same JvmName .

By declaring an object in Kotlin we define a singleton, that is, a class with only one instance. Such an instance is created lazily, the first time it’s used, in a thread-safe manner.

For example, we could define the following object to group the functions and values we defined above:

Then, differently than before, we have to specify the name of the object to access its functions. In other words, an object defines a scope:

As there’s only one instance of each Kotlin object , the qualified name of the object is enough to access its members. This is similar to but slightly different than a Java class consisting of static methods or variables only. In the latter case, we could instantiate that Java class as many times as we wanted (assuming the constructor is not private ). In that case, the static variables would be the same for each different instance of the class. With Kotlin object s, on the other hand, we only have one instance.

In the example above, PointFactory is pretty tied to the Point class, as it contains several methods to instantiate a point. For cases like this, we can make it a companion object , making this tight coupling more explicit:

With companion object s, we can declare methods and tie them to a given class, rather than to its instances. As for “normal” object s, companion object s are singletons. Hence, we can reference the functions by specifying the name of the class:

Kotlin provides us with three different solutions to define static methods or fields.

Package-level functions and values are the most idiomatic way. Often there’s no need to scope utility methods inside a class. In such cases, package-level members are a fine choice allowing for greater reusability of the code. As a matter of fact, most of the standard library is implemented using them.

However, object s and companion object s do have some pros. For example, they allow for a better scoping of methods and fields. One of the main cons of package-level members is that they pollute the auto-completion suggestions available in most IDEs, making it more difficult to pick the right function. The scope of an object solves this issue.

Strictly speaking, in a pure object-oriented programming mindset, everything is better defined inside of a class. However, as we saw above, often we need methods that are different to place in an existing class. This can happen, for example, with utility methods that operate on a class but do not represent the behavior of that class.

In languages like Java, the normality is to define Utils or Helper classes full of the methods that are different to scope in a certain class. This gets easily out of control and leads to classes with different responsibilities and heterogeneous methods that are very difficult to read, maintain, and re-use.

Kotlin, on the hand, is not just an object-oriented language. It supports other programming paradigms, such as the functional one. Hence, it does not take the object orientation as strictly as Java, allowing us, for example, to define functions that are not tied to any class.

On the one hand, this improves the reusability and the maintainability of the code. Furthermore, we can use the package structure and the visibility keywords to choose which portion of our codebase can use a given function or object . Better still, with companion object s, we can define utility code as close as possible to the class it operates on. On the other hand, we ought to pay attention to the freedom and flexibility of Kotlin’s approach. For example, nothing prevents us from defining a mutable package-level variable, essentially a global one, which can be very harmful.

As is common with modern programming languages, we have a number of ways to model the same thing and achieve the same result. Hence, it is always a matter of experience and sensibility to figure out what the right construct is and to use it appropriately.

LogRocket : Instantly recreate issues in your Android apps.

how to create a static method in kotlin

LogRocket is an Android monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your Android apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.

Start proactively monitoring your Android apps — try LogRocket for free .

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)

how to create a static method in kotlin

Stop guessing about your digital experience with LogRocket

Recent posts:.

Million Js Adoption Guide: Overview, Examples, And Alternatives

Million.js adoption guide: Overview, examples, and alternatives

Million.js is an open source, minimalistic JavaScript compiler designed to revolutionize and improve React performance.

how to create a static method in kotlin

daisyUI adoption guide: Overview, examples, and alternatives

daisyUI is an open source component library built on top of Tailwind CSS designed to enhance the DX for web designers and developers.

how to create a static method in kotlin

Using Chrome’s Document Picture-in-Picture API in React

Chrome’s new Document Picture-in-Picture API builds on the PIP API to open up a wider range of possibilities for user interaction.

how to create a static method in kotlin

Vercel v0 and the future of AI-powered UI generation

Vercel v0 is a powerful tool for rapidly prototyping various UI elements that generates code based on plain text descriptions.

how to create a static method in kotlin

Leave a Reply Cancel reply

  • TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • Kotlin Java
  • Kotlin Tutorial
  • Setup Kotlin(Java) Project
  • Kotlin Example Program
  • Convert Java file to Kotlin
  • main() function
  • Kotlin – For Loop
  • Kotlin – While Loop
  • Kotlin – Do-while Loop
  • Kotlin – break
  • Kotlin – continue
  • Kotlin – For i in range
  • Kotlin – Infinite While loop
  • Kotlin Ranges
  • Array Basics
  • Kotlin – Create Array
  • Kotlin – Create Empty Array
  • Kotlin – Create Integer Array
  • Kotlin – Create String Array
  • Kotlin – Create Byte Array
  • Kotlin – Array of Arrays
  • Kotlin – Get Array Size
  • Kotlin – Get Element of Array at Specific Index
  • Kotlin – Set Element of Array at Specific Index
  • Kotlin – Get First Element of Array
  • Kotlin – Get Last Element of Array
  • Kotlin – Print Array in Single Line
  • Array Checks
  • Kotlin – Check if Array is Empty
  • Kotlin – Check if Array Contains Specified Element
  • Array Loops
  • Kotlin – Iterate over Array
  • Kotlin – Array For Loop
  • Kotlin – Array While Loop
  • Array Sorting
  • Kotlin – Array Sorting
  • Kotlin – Sort Array of Integers
  • Kotlin – Sort Array of Strings
  • Kotlin – Sort Array of Strings based on Length
  • Kotlin – Sort Array in Descending Order
  • Kotlin – Classes and Constructors
  • Kotlin – Sealed Class
  • Kotlin – Data Class
  • Kotlin – Enum
  • Kotlin – Extension Functions
  • Inheritance
  • Kotlin – Inheritance
  • Kotlin – Override Method of Super Class
  • Abstraction
  • Kotlin – Abstraction
  • Kotlin – Abstract Class
  • Kotlin – Interfaces
  • Kotlin Try Catch
  • Kotlin – Throw Exception
  • Kotlin – Create custom Exception
  • Kotlin – Initialize string
  • Kotlin – Create empty string
  • Kotlin – Define a string constant
  • Kotlin – Get string length
  • Kotlin – Print a string
  • Kotlin – Concatenate strings
  • Kotlin – Compare strings
  • Kotlin – Multiline strings
  • Kotlin – Check if strings are equal
  • Kotlin – Check if strings are equal ignoring case
  • Kotlin – Check if string is empty
  • Kotlin – Check if string contains specific substring
  • Kotlin – Check if string contains specific character
  • Kotlin – Check if string starts with specific prefix
  • Kotlin – Check if string starts with specific character
  • Kotlin – Check if string ends with specific suffix
  • Kotlin – Check if string ends with specific character
  • Kotlin – Check is string matches regular expression
  • Kotlin – Count number of words in string
  • Kotlin – Find index of substring
  • Kotlin – Get random character from string
  • Kotlin – Substring
  • Transformations
  • Kotlin – Capitalize a string
  • Kotlin – Convert string to lowercase
  • Kotlin – Convert string to uppercase
  • Kotlin – Filter characters of string
  • Kotlin – Join strings by a separator
  • Kotlin – Remove first N characters from string
  • Kotlin – Remove last N haracters from string
  • Kotlin – Repeat string N times
  • Kotlin – Reverse a string
  • Kotlin – Sort characters in string
  • Kotlin – String replace
  • Kotlin – Trim white spaces around string
  • Split Operations
  • Kotlin – Split string
  • Kotlin – Split string to lines
  • Kotlin – Split string by comma
  • Kotlin – Split string by single space
  • Kotlin – Split string by any whitespace character
  • Kotlin – Split string by one or more spaces
  • Conversions
  • Kotlin – Convert char array to string
  • Kotlin – Convert string to char array
  • Kotlin – Convert byte array to string
  • Kotlin – Convert string to byte array
  • Kotlin – Convert string to list of characters
  • Kotlin – Convert list of characters to string
  • Kotlin – Convert string to set of characters
  • Character specific Operations
  • Kotlin – Get character at specific index in string
  • Kotlin – Get first character in string
  • Kotlin – Get last character in string
  • Kotlin – Iterate over each character in string
  • Kotlin – Insert character at specific index in string
  • Kotlin – Get unique characters in string
  • Kotlin – Remove character at specific index in string
  • Kotlin – Remove first character in string
  • Kotlin – Remove last character in string
  • Kotlin – Replace specific character with another in a string
  • Kotlin – Remove specific character in a string
  • String Formatting
  • Kotlin – Write variable inside string
  • String Collections
  • Kotlin – List of strings
  • Kotlin String List – Filter based on Length
  • Kotlin – Filter only strings in this list
  • Kotlin List – Filter non-empty strings
  • Kotlin – Create a set of strings
  • Kotlin – Create string array
  • Kotlin – Sort array of strings
  • Kotlin – Sort string array based on string length
  • Create Operations
  • Kotlin – Create file
  • Kotlin – Create a directory
  • Kotlin – Create directory recursively
  • Get Properties / Meta
  • Kotlin – Get file creation timestamp
  • Kotlin – Get file extension
  • Kotlin – Get file last modified timestamp
  • Kotlin – Get file name
  • Kotlin – Get file size
  • Iterate over files
  • Kotlin – Iterate through all files in a directory
  • File Checks
  • Kotlin – Check if file exists
  • Kotlin – Check if file is readable
  • Kotlin – Check if file is writable
  • Kotlin – Check if directory exists
  • Read Operations
  • Kotlin – Read file
  • Kotlin – Read file as list of lines
  • Kotlin – Read file character by character
  • Kotlin – Read file line by line
  • Kotlin – Read file into a string
  • Write / Update Operations
  • Kotlin – Append to text file
  • Kotlin – Copy content of a file to another file
  • Kotlin – Copy directory
  • Kotlin – Copy file
  • Kotlin – Move file
  • Kotlin – Move directory
  • Kotlin – Rename file
  • Kotlin – Rename directory
  • Kotlin – Replace specific string in file
  • Kotlin – Write to File
  • Delete Operations
  • Kotlin – Delete a file
  • Kotlin – Delete / remove all content in text file
  • Kotlin – Delete a directory
  • Kotlin - Convert List to Set
  • Kotlin - Create an empty list
  • Kotlin - Filter elements of a List based on Condition
  • Kotlin - Filter even numbers in a list
  • Kotlin - Filter List of strings based on length
  • Kotlin - Filter Odd Numbers in a list
  • Kotlin - Filter only integers in a list
  • Kotlin - Filter only non-empty strings of a list
  • Kotlin - Filter only strings from a list
  • Kotlin - Iterate over Elements of List using For Loop in Kotlin?
  • HKotlin - Iterate over List of Lists
  • Kotlin - Remove all occurrences of element in a list
  • Kotlin - Remove all Elements from a List
  • Kotlin - Remove specific Element in list
  • Kotlin - Access index of element in a list while filtering
  • Kotlin - Add element to List at specific index
  • Kotlin - Add Element to List
  • Kotlin - Define a List of Integers
  • Kotlin - Define a List of Lists
  • Kotlin - Define a List of strings
  • Kotlin - Read file content as a list of lines
  • Kotlin - Remove element at specific index in list
  • Kotlin - replace an Element at specific Index
  • Kotlin List forEach – Example
  • Kotlin List.all()
  • Kotlin List.any()
  • Kotlin List.component1()
  • Kotlin List.component2()
  • Kotlin List.component3()
  • Kotlin List.component4()
  • Kotlin List.component5()
  • Kotlin List.contains()
  • Kotlin List.containsAll()
  • Kotlin List.count()
  • Kotlin List.get()
  • Kotlin List.indexOf()
  • Kotlin List.indices Property
  • Kotlin List.isEmpty()
  • Kotlin List.iterator()
  • Kotlin List.lastIndex
  • Kotlin List.lastIndexOf()
  • Kotlin List.size
  • Kotlin List.subList()
  • Kotlin Mutable List
  • Kotlin – Add two numbers
  • Kotlin – Armstrong number
  • Kotlin – Average of two numbers
  • Kotlin – Average of numbers given in array
  • Kotlin – Check if given number is part of Fibonacci series
  • Kotlin – Check prime number
  • Kotlin – Even number
  • Kotlin – Factorial
  • Kotlin – Factors of a number
  • Kotlin – Fibonacci series
  • Kotlin – Find largest of two numbers
  • Kotlin – Find smallest of two numbers
  • Kotlin – Find largest of three numbers
  • Kotlin – Find smallest of three numbers
  • Kotlin – Odd number
  • Kotlin – Palindrome
  • Kotlin – Print prime numbers
  • Kotlin – Product of digits in a number
  • Kotlin – Reverse a number
  • Kotlin – Sum of first n natural numbers
  • Kotlin – Sum of squares of first n natural numbers
  • Kotlin – Sum of digits in a number
  • Kotlin Interview Questions
  • Related Tutorials
  • Kotlin Android Tutorial
  • How to Learn Programming
  • ❯ Kotlin Tutorial

How to write Static Method in Kotlin?

In this tutorial, you shall learn how to write a static method in a class in Kotlin, with examples.

Static Method in Kotlin

Unlike Java, we do not have a static keyword in Kotlin. But, that does not limit us to write methods in Kotlin that function as static methods in Java.

To achieve the functionality of a static method in Kotlin, use companion keyword modifier.

In the following example, we define a class MyClass with with a function greetings() , where the function is modified using companion keyword. We can call this method using Class name as MyClass.greetings() .

Kotlin Program

In this Kotlin Tutorial , we learned how to call a method using Class name, without instantiating an instance of the class type.

Popular Courses by TutorialKart

App developement, web development, online tools.

How to create static variables and functions in Kotlin

how to create a static method in kotlin

The val keyword is used to create an immutable variable, just like the final keyword in java.

Take your skills to the next level ⚡️

  • Collections
  • Android Studio
  • Kotlin Android
  • Android Projects
  • Android Interview Questions

Equivalent of Java Static Methods in Kotlin

Prerequisite : static Keyword in Java

Static Keyword in Java is a non-access modifier. It is useful for representing meta-data (usually data related to a class). The static keyword serves for efficient memory management as in spite of recurring usages the Java Virtual Machine only once allocates memory for the variable, method, class or block declared as static. Static members are not related to instances being created but are owned by the class itself. In Kotlin however, we don’t have such keywords. So this functionality has to be achieved using some other ways. The most popular methods of implementing functionality similar to that of the static keyword are listed below:

By the use of companion object

Object expressions or Object declarations in Kotlin are used to create instances of an anonymous class. Using companion identifiers along with such object expressions or declarations facilitates members of the companion object to be called just by using the class name as the qualifier. When the matching class is loaded (resolved), a companion object is created that has the same semantics as a Java static initializer.

 

In the case of Java, the method of companion object can be called but we need an additional ‘Companion’ field to be added before the function call after the class name. We can get rid of this too, by either giving our own name to the companion object or by using @JvmStatic annotation.

By using @JvmStatic annotation

Adding @JvmStatic annotation simply before the members to be declared as the equivalent of static ones in Java works well in Kotlin to provide the same functionality.

 

By using a package-level function

An equivalent functionality as that of the static members and methods in Java can also be achieved by making that member, method, class, or block be a package-level member. This can be done by creating a .kt file and placing all such desired members into it without making any class inside. In this way, all these members will be compiled by the JVM as the static parts of the Kotlin class in which the package is being imported.

Kotlin File to achieve the functionality of static keyword:

Main Kotlin File:

 

author

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

Trending Articles on Technical and Non Technical topics

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Kotlin static methods and variables

In Java, once a method is declared as "static", it can be used in different classes without creating an object. With static methods, we don't have to create the same boilerplate code for each and every class. Here we will take an example to demonstrate how Kotlin implements static methods.

Example – Static Method in Kotlin using Companion Object

In order to implement a static method in Kotlin, we will take the help of "companion objects".

Companion objects are the singleton objects whose properties and functions are tied to a class but not to the instance of that class. Hence, we can access them just like a static method of the class.

Note that only one companion class is allowed per class. More than one companion object per class will lead to a runtime error in Kotlin.

On execution, it will generate the following output −

Soumak De

Related Articles

  • Demonstrate static variables, methods and blocks in Java
  • Where and how to use static variables in Android using Kotlin?
  • Declare static variables and methods in an abstract class in Java
  • What is the equivalent of Java static methods in Kotlin?
  • Static and non static blank final variables in Java
  • Class and Static Variables in Java
  • Class and Static Variables in C#
  • Templates and Static variables in C++
  • Static variables in Java
  • Static Variables in C
  • C++ static member variables and their initialization
  • Static methods vs Instance methods in Java
  • Initialization of global and static variables in C
  • Final static variables in Java
  • How do I create static class data and static class methods in Python?

Kickstart Your Career

Get certified by completing the course

How can I create a static class in Kotlin? (static CLASS not method or variable)

Hello everyone,

I am looking for a way to create a static class in Kotlin. One example is when I want to use JavaFX, I normally need to create a static class that inherit the Application class, and sometimes I also want to create some inner classes that are static. Of course, I have a way to deal with this problem in the former case, but I want to know a general way to create Java static class in Kotlin because I am translating a lot of Java code to Kotlin which has a lot of static classes and did not work using the default translation in IDEA.

Thank you. I am looking forward to hearing from you.

As long as you mean static nested classes, in kotlin a nested class is static by default. To make it a non-static inner class it needs to have a inner flag.

You could use a companion object . If you want a singleton you could also use an object class .

:smiley:

Related Topics

Topic Replies Views Activity
Language Design 0 718 August 11, 2020
Language Design 2 7866 March 30, 2019
Language Design 0 1133 March 15, 2018
3 2685 April 10, 2012
3 1018 March 9, 2012

Mock Static Java Methods Using Mockk

Last updated: March 19, 2024

how to create a static method in kotlin

As a seasoned developer, you’re likely already familiar with Spring. But Kotlin can take your developer experience with Spring to the next level!

Join the >> "Advanced Kotlin Techniques for Spring Developers" webinar and learn how to:

Add new functionality to existing classes with Kotlin extension functions.

Use Kotlin bean definition DSL.

Better configure your application using lateinit.

Use sequences and default argument values to write more expressive code.

By the end of this talk, you’ll have a deeper understanding of the advanced Kotlin techniques that are available to you as a Spring developer, and be able to use them effectively in your projects.

1. Overview

Kotlin has great compatibility with Java, but one difference is that Kotlin doesn’t contain the static modifier , and when it comes to mocking, Java static methods aren’t convenient to access. The mocking library Mockk  has a feature that allows us to mock static Java methods easily.

In this tutorial, we’ll learn how to use this function and undo its effects after we’re done with it.

2. Using Mockk on a Java static Method

To set up our demonstration, let’s use RandomNumberGenerator as an example of a static Java class. We assume that this is whatever static method our external implementation gives us:

Let’s use it in a simple example to determine the result of a coin flip based on the class we have created:

Some unit tests won’t require any change or mocking to work. Validating that our coin flip never throws an exception is an example of that:

In some other cases, however, we might want to assert the mechanisms behind our flip, which is the static random() method. For example, we may need to validate specific rules based on the result of the method call.

In our sample function, the assertion we want depends on an assumption: Whenever the static method is called, we’ll replace it with a class that returns what we want . The test should have a format similar to:

To make sure we can control the returned value, let’s use  mockkStatic() to fine-tune the result:

3. Removing a Mockk After Using It

We need to ensure we don’t mess with the static namespace we used, as many other methods might use the same static method . In other words, we don’t want our mocked behavior to leak into other tests. So, let’s unmock the static class we mocked previously:

4. Removing All Mockks at Once After Tests

We can also unmock what we’ve mocked after any test finishes running by using unmockkAll() . That limits the unmockk calls to a single place and ensures we won’t leak any modification to the rest of our test suite.

To do that, let’s add a method to our unit test class and annotate it with @AfterEach :

5. Conclusion

In this tutorial, we’ve learned how to use Mockk’s mockkStatic to mock static Java methods. We also prepared our test suite to unmockk any mocks we might have set up, ensuring we don’t pollute the context for other tests.

As always, the implementation used in this article can be found on GitHub .

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Possibility to call a Java static method in Kotlin

Suppose we have a Java static method:

It is possible to call that method in Kotlin?

Naetmul's user avatar

4 Answers 4

Yes, you can. Java code:

Kotlin code:

0wl's user avatar

  • 2 but from instance is not? –  qwert_ukg Commented Mar 15, 2018 at 5:53
  • How could we call android.nfc.Tag.createMockTag from Kotlin? –  IgorGanapolsky Commented Aug 20, 2020 at 19:14

The answer from 0wl is generally correct.

I just wanted to add that some of the Java classes are mapped to special Kotlin classes. In this case you must fully qualify the Java class for this to work.

Eric Obermühlner's user avatar

Yes . It's documented in the Java Interop

http://kotlinlang.org/docs/reference/java-interop.html

The docs show the following example

The only caveat I see is that they can't be passed around with an instance and accessed on instances of the class like you can in Java but this is usually considered bad practice anyway.

Lionel Port's user avatar

In Java it is possible to call static methods from child classes, in Kotlin this is not possible. If this is your case, call the method from the parent, instead.

Test.java :

Refer to this StackOverflow thread for more information.

Maicon Mauricio's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java methods static kotlin interop or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Does Matthew 7:13-14 contradict Luke 13:22-29?
  • Have children's car seats not been proven to be more effective than seat belts alone for kids older than 24 months?
  • Are there any CID episodes based on real-life events?
  • What is the best catalog of black hole candidates?
  • Old book about a man who finds an abandoned house with a portal to another world
  • Is there any legal justification for content on the web without an explicit licence being freeware?
  • Does it matter if a fuse is on a positive or negative voltage?
  • À + infinitive at start of sentence
  • Could a transparent frequency-altering material be possible?
  • Were there engineers in airship nacelles, and why were they there?
  • What could explain that small planes near an airport are perceived as harassing homeowners?
  • Is it consistent with ZFC that the real line is approachable by sets with no accumulation points?
  • Exception handling: is one exception type sufficient?
  • How to fix misaligned objects that look fine in viewport but not in render?
  • Weird behavior by car insurance - is this legit?
  • How would I say the exclamation "What a [blank]" in Latin?
  • Where can I access records of the 1947 Superman copyright trial?
  • Reconstructing Euro results
  • Is there a way to non-destructively test whether an Ethernet cable is pure copper or copper-clad aluminum (CCA)?
  • How to "refresh" or "reset" the settings of a default view?
  • In By His Bootstraps (Heinlein) why is Hitler's name Schickelgruber?
  • What type of black color text for brochure print in CMYK?
  • Trying to determine what this small glass-enclosed item is
  • How many steps are needed to turn one "a" into 100,000 "a"s using only the three functions of "select all", "copy" and "paste"?

how to create a static method in kotlin

IMAGES

  1. Static Factory Method Exercise in Kotlin

    how to create a static method in kotlin

  2. How to create Kotlin static function or method

    how to create a static method in kotlin

  3. #127 Kotlin Tutorial

    how to create a static method in kotlin

  4. Kotlin Static Function

    how to create a static method in kotlin

  5. Kotlin Static Variable And Its Practical Application

    how to create a static method in kotlin

  6. kotlin

    how to create a static method in kotlin

VIDEO

  1. 203 create static method

  2. #107 Kotlin Tutorial

  3. Object.create

  4. #7 Kotlin Programming Tutorial

  5. Static Method in Abstract Class

  6. Dissecting NavController: Jetpack Compose

COMMENTS

  1. How to create static methods and classes in Kotlin

    Package-level functions and values are syntactic sugar for static fields and methods in Java. What the Kotlin compiler does is generate a Java class named after the Kotlin file, with static methods and fields in it. For example, the functions in com.logrocket.blog.utils.factory.kt will be compiled into a class named com.logrocket.blog.utils ...

  2. What is the equivalent of Java static methods in Kotlin?

    class Foo {. companion object {. @JvmStatic. fun a() : Int = 1; } } and then it will exist as a real Java static function, accessible from both Java and Kotlin as Foo.a(). If it is just disliked for the Companion name, then you can also provide an explicit name for the companion object looks like this: class Foo {.

  3. Static Methods Behavior in Kotlin

    In this quick tutorial, we'll see a few ways to achieve Java's static method behavior in Kotlin. 2. Package-Level Functions. Let's start by creating a LoggingUtils.kt file. Here, we'll create a very simple method called debug. Since we don't care much about the functionality inside our method, we'll just print a simple message.

  4. How to write Static Method in Kotlin?

    To achieve the functionality of a static method in Kotlin, use companion keyword modifier. Example. In the following example, we define a class MyClass with with a function greetings(), where the function is modified using companion keyword. We can call this method using Class name as MyClass.greetings().

  5. Static Methods and Companion Objects in Kotlin

    In Kotlin, it is advisable to define methods at the package level to achieve the functionality of static methods. Let's define a new Kotlin file and name it Static. Within this file, we will place the code for a function that will return the first character of the input string (if the input is empty, an exception will be raised), which is as ...

  6. How to create Kotlin static function or method

    Unlike Java programming language, Kotlin doesn't have a static modifier that you can use to define static functions (methods) of a class. Instead of using the static modifier, Kotlin allows you to create a companion object inside a class to declare static functions. The following Java code: is equivalent to the following Kotlin code: In both ...

  7. How to create static variables and functions in Kotlin

    In Kotlin, you have the const keyword that's equal to the static keyword in Java. The const keyword is used to create a variable that's known to Kotlin before the compilation, so you don't need to create an instance of a class to use it. The val keyword is used to create an immutable variable, just like the final keyword in java.

  8. How to Create "static" methods for Enum in Kotlin

    First, regarding the terminology of "method" or "function", in this tutorial, when we talk about Kotlin, we'll use "function". "Method" will be used for the Java context. In Java, we can add static methods to an enum to do some common operations on the enum instances. However, unlike Java, Kotlin doesn't have the static keyword.

  9. Equivalent of Java Static Methods in Kotlin

    Unlike Java, Kotlin doesn't support static methods for a class. Most readers will know that static methods do not belong to the object instance but rather to the type itself. In Kotlin, it is advisable to define methods at the package level to achieve the functionality of static methods. Let's define a new Kotlin file and name it Static. Within thi

  10. Kotlin static methods and variables

    Get Started. Kotlin static methods and variables - In Java, once a method is declared as static, it can be used in different classes without creating an object. With static methods, we don't have to create the same boilerplate code for each and every class. Here we will take an example to demonstrate how Kotlin implements static methods.Example .

  11. Creating Java static final Equivalents in Kotlin

    As the code shows, similar to accessing variables declared in the Kotlin object in Java, if it's a const variable, we can access it directly. However, if it's a regular val variable, we need to get its value through the getter method. Similarly, we can add the @JvmField annotation to make this variable a static final variable in Java. We ...

  12. Daily Kotlin: Static methods

    Source:Giphy. But, if you want to do it just like the old style Java, i.e. by using class name as a qualifier, you need companion identifier.. class SampleClass{companion object {fun bar()= print ...

  13. Calling Kotlin from Java

    Static methods. As mentioned above, Kotlin represents package-level functions as static methods. Kotlin can also generate static methods for functions defined in named objects or companion objects if you annotate those functions as @JvmStatic. If you use this annotation, the compiler will generate both a static method in the enclosing class of ...

  14. Static Initialization Block in Kotlin

    Static Initialization. In Java, to initialize static components of a class, we can use static initializer blocks: static {. // put static initializers here. } There are no static members and static initializers in Kotlin, at least similar to what Java has. However, we can use a companion object to achieve the same thing in Kotlin: class Static {.

  15. java

    From some point of view, companion object s in Kotlin are equivalent to static parts of Java classes. Particularly, they are initialized before class' first usage, and this lets you use their init blocks as a replacement for Java static initializers: companion object {. init {. //here goes static initializer code.

  16. How can I create a static class in Kotlin? (static CLASS not method or

    Hello everyone, I am looking for a way to create a static class in Kotlin. One example is when I want to use JavaFX, I normally need to create a static class that inherit the Application class, and sometimes I also want to create some inner classes that are static. Of course, I have a way to deal with this problem in the former case, but I want to know a general way to create Java static class ...

  17. Kotlin How to create Static Members for class

    Kotlin doesn't have static member for class, it's mean that you can't create static method and static variable in Kotlin class. Fortunately, Kotlin object can handle this. If you declare a ...

  18. java

    How i have to make static method, that returns an AppComponent? java; android; kotlin; dependency-injection; static-methods; Share. Improve this question. Follow ... Might want to move appComponent to the companion object in the Kotlin version to make it static too. Share. Improve this answer. Follow answered May 14, 2021 at 16:59. Kilian ...

  19. Mock Static Java Methods Using Mockk

    The mocking library Mockk has a feature that allows us to mock static Java methods easily. In this tutorial, we'll learn how to use this function and undo its effects after we're done with it. 2. Using Mockk on a Java static Method. To set up our demonstration, let's use RandomNumberGenerator as an example of a static Java class.

  20. Is it possible to specify a static function in a Kotlin interface

    For future uses, it's also possible to give the child class to a function as a receiver parameter: val encodableClass = EncodableClass("Some Value") //The encode function is accessed like a member function on an instance val stringRepresentation = encodableClass.encode() //The decode function is accessed statically val decodedClass = EncodableClass.decode(stringRepresentation) interface ...

  21. Possibility to call a Java static method in Kotlin

    In Java it is possible to call static methods from child classes, in Kotlin this is not possible. If this is your case, call the method from the parent, instead. Test.java: public class Test {. public static void printFoo() {. System.out.println("foo");