First, explain
Each class can correspond to a companion object
The members of the companion object are unique
Members of companion objects are similar to static members of Java
2, In Java
Methods calling the kotlin class need to add
@JvmStatic
To call the member variable of the kotlin class, you need to add
@JvmField
3, Like the math class in java.lang package
All its methods are static. When using, you can directly use math.xxx (method)
4, Like the method in the Integer class, this is used in Java
Integer a = Integer.valueOf(3);
5, In Kotlin, forms like this can be called directly
Take a look at the code
Integer a = Integer.valueOf(3);
6, Take a look at an example
Let's take a look at the classes in kotlin
package net.println.kotlin.chapter4
/**
* @author:wangdong
* @description:Companion objects and static members
*/
fun main(args: Array<String>) {
//val a = minOf(args[0].toInt(),args[1].toInt())
//Use the following definition
val latitude = Latitude.ofDouble(40.3)
val latitude2 = Latitude.ofLatitude(latitude)
println(Latitude.TAG)
}
/**Define a latitude class*/
class Latitude private constructor(val value: Double){
//Class
companion object {
//Define a static method
@JvmStatic
fun ofDouble(double: Double): Latitude {
return Latitude(double)
}
//Define a static method
@JvmStatic
fun ofLatitude(latitude: Latitude): Latitude {
return Latitude(latitude.value)
}
//Define a static variable
@JvmField
val TAG: String = "hello"
}
}
Take a look at Java
package net.println.kotlin.chapter4;
/**
* @author:wangdong
* @description:Calling Latitude method in java
*/
public class StaticJava {
Integer a = Integer.valueOf(3);
public static void main(String[] args) {
//You need to call the company to call the method
Latitude latitude = Latitude.Companion.ofDouble(54.4);
//You can add an annotation @ JvmStatic to the method in Latitude
Latitude latitude2 = Latitude.ofDouble(54.87);
System.out.println(Latitude.TAG);
}
}
End