I added a function to Math
class in the Kotlin but I could not use it, I did this before with MutableList
and it worked but I can not do it with Math
class.
fun Math.divideWithSubtract(num1: Int, num2: Int) =
Math.exp(Math.log(num1.toDouble())) - Math.exp(Math.log(num2.toDouble()))
For doing this we create an extension function for MutableList<> with swap() function. The list object call the extension function (MutableList<Int>. swap(index1: Int, index2: Int):MutableList<Int>) using list. swap(0,2) function call.
Actually, it doesn't matter to where you writing them. The extension function are mapped with a class which is already a part of your application. So, it's up to you in which you are going write you extension functions.
In Kotlin we use a single colon character ( : ) instead of the Java extends keyword to extend a class or implement an interface. We can then create an object of type Programmer and call methods on it—either in its own class or the superclass (base class).
Are you using Intellij IDEA or Android Studio? Open a Kotlin file that has extension functions, go to Tools -> Kotlin -> Show bytecode, and from the bytecode window that pops up choose Decompile. You'll see what the Java analog of that code looks like and it'll quickly become apparent what the trick is!
You can't use this extension on Math on a static level because extensions only work on instances. edit: Since Math cannot be instantiated, you won't be able to use extensions on it.
If you really want that method as an extension, you should extend Int instead :
fun Int.divideWithSubtract(otherInt: Int) =
Math.exp(Math.log(this.toDouble())) - Math.exp(Math.log(otherInt.toDouble()))
And you would use it like this :
val result = 156.divideWithSubstract(15) //:Double
If you really want to have static-ish methods, in Java and Kotlin as well, you could always define any method on package level in a kotlin file.
Thus, some doSomething(args)
method in a Util.kt
file would be accessible anywhere in any Kotlin file and you would have to call UtilKt.doSomething()
in Java.
see : Package level functions in the official doc
You cannot use it like static java methods, but only on Math
objects.. That is why it worked on MutableList
because you used it on a list.
Why would you want to extend Math
here? Extending makes sense, when you have a receiver type (like String
e.g.), whose instances you want to extend. Math is just a util class and cannot be instantiated, i.e. it's not possible to provide an appropriate receiver to the function.
Just create this method on top level for example:
fun divideWithSubtract(num1: Int, num2: Int) =
Math.exp(Math.log(num1.toDouble())) - Math.exp(Math.log(num2.toDouble()))
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