Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static method imports in Kotlin

Tags:

kotlin

How can a method be statically imported in Kotlin? For example, in Java it's possible to do:

... import static org.mockito.Mockito.verify; ... class FoobarTest {      ...      @Test public void testFoo() {           verify(mock).doSomething();      }  } 

How can the same be done in Kotlin without having to fully qualify the method every time with Mockito.verify(mock).doSomething()?

like image 470
memoizr Avatar asked Oct 10 '15 14:10

memoizr


People also ask

Can you import a static method?

With the help of import, we are able to access classes and interfaces which are present in any package. But using static import, we can access all the static members (variables and methods) of a class directly without explicitly calling class name.

How does Kotlin implement static methods?

Android Dependency Injection using Dagger with Kotlin 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.

How do I import a package to Kotlin?

Overview. A package is a group of related classes, enums, functions, sub-packages, and so on. To import a package in Kotlin, we use the import keyword, followed by the name of the package that needs to be imported.

Does Kotlin have static methods?

In Kotlin, we can achieve the functionality of a static method by using a companion identifier. For example, If you want to create a method that will return the address of your company then it is good to make this method static because for every object you create, the address is going to be the same.


1 Answers

It turns out it's very easy. To import a single static method:

import org.mockito.Mockito.verify 

And to import everything:

import org.mockito.Mockito.* 

so it will be possible to do

`when`(someMock.someAction).thenReturn(someResult) verify(mock).doSomething() 
like image 185
memoizr Avatar answered Sep 19 '22 22:09

memoizr