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...
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With