Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one add static methods to Java classes in Kotlin

Is it possible to add a new static method to the java.lang.Math class in Kotlin? Usually, such things are possible in Kotlin thanks to Kotlin Extensions.

I already tried doing the following in a file I made called Extensions.kt:

fun Math.Companion.clamp(value:Double,minValue:Double,maxValue:Double):Double {     return Math.max(Math.min(value,maxValue),minValue) } 

but Math.Companion could not be resolved...

like image 301
Eric Avatar asked Nov 25 '15 08:11

Eric


People also ask

How do I create a static method in Kotlin?

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.

Can we create static methods in Kotlin?

Kotlin is a statically typed programming language for the JVM, Android and the browser, 100% interoperable with Java. Blog of JetBrains team discussing static constants in Kotlin.

Why there is no static in Kotlin?

Kotlin is known primarily as a drop-in replacement for Java, but it gets rid of a well-known Java construct: the static keyword. Instead, that class-level functionality is offered mainly by companion objects.

How do you override a static method in Kotlin?

What you can do is to subclass the parent and add a new companion object that has a method with the same name as the parent and call the parent method from inside. Static methods can't be overridden. It's called shadowing as you hide a method with another one.


2 Answers

As of Kotlin 1.3, this is not possible. However, it's being considered for a future release!

To help this feature get implemented, go vote on this issue: https://youtrack.jetbrains.com/issue/KT-11968

This idea is very popular in the Kotlin community, so I bet it'll be in soon enough.

like image 68
Ky. Avatar answered Oct 08 '22 11:10

Ky.


I think this is not possible. Documentation says the following:

If a class has a companion object defined, you can also define extension functions and properties for the companion object.

The Math class is a Java class, not a Kotlin one and does not have a companion object in it. You can add a clamp method to the Double class instead.

like image 38
aga Avatar answered Oct 08 '22 12:10

aga