6

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()))
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
Ali Urz
  • 107
  • 3
  • Suggested reading: https://stackoverflow.com/questions/35317940/when-should-one-prefer-kotlin-extension-functions – BakaWaii Aug 18 '17 at 05:28

3 Answers3

9

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

Oyzuu
  • 351
  • 1
  • 4
  • 12
4

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.

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
3

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()))
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196