简体   繁体   中英

Java Math like classes in Kotlin

How we can create Java Math like Util classes in Kotlin . So that I can call something like Math.add() . I try to do using companion object. Let me know if there is another way to do it.

You can just use a simple object declaration to achieve that syntax:

object Math {
    fun add(x: Int, y: Int) = x + y
}

This creates a singleton class, with only one instance at runtime, and you can call the methods on this instance with the Math.add(1, 4) syntax.


Companion objects are just special cases of these object declarations nested inside classes, with their members accessible through the container class's identifier, similarly to static functions in Java.

You can actually nest any object inside a class, the companion keyword just lets you create them without an explicit name.

Example of named nested objects:

class A {
    fun a() {}
    object B {
        fun b() {}
    }
    companion object {
        fun o() {}
    }
}

These functions can then be called like this:

A().a()          // this call of course needs an instance of A
A.B.b()
A.Companion.o()
A.o()

You can do this like

    class Math {
        companion object {
            fun add(val x: Int, val y: Int): Int {
                return x+y
            }
            fun subtract(val x: Int, val y: Int): Int {
                return x-y
            }
            fun multiply(val x: Int, val y: Int): Int {
                return x*y
            }
            ...
        }
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM