Add an extensions function to Math class in kotlin

Ali Urz :

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()))
Xalamadrax :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=465508&siteId=1