[英]Java Math like classes in Kotlin
How we can create Java
Math like Util classes in Kotlin
. 我们如何在
Kotlin
像Util类一样创建Java
Math。 So that I can call something like Math.add()
. 这样我就可以调用
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
声明来实现该语法:
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. 这将创建一个单例类,在运行时只有一个实例,您可以使用
Math.add(1, 4)
语法在此实例上调用方法。
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. 伴侣对象只是这些
object
声明嵌套在类中的特例,其成员可以通过容器类的标识符进行访问,类似于Java中的静态函数。
You can actually nest any object inside a class, the companion
keyword just lets you create them without an explicit name. 实际上,您可以将任何对象嵌套在一个类中,
companion
关键字仅允许您在没有显式名称的情况下创建它们。
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
}
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.