Static trong Java
Trong Java, static dùng cho biến/phương thức thuộc class, không cần tạo instance. Ví dụ:
public class Test {
static int myStaticVariable = 10;
static void staticMethod() {
System.out.println("www.tutorialspoint.com");
}
public static void main(String[] args) {
staticMethod();
System.out.println("Accessing Static variable-" + myStaticVariable);
}
}
Tương đương trong Kotlin
Kotlin không có từ khóa static. Có 2 cách đạt được tương tự:
- Companion object
- Object class + @JvmStatic
Cách 1: Companion Object
companion object bên trong class cho phép truy cập thành viên mà không cần instance. Nó được khởi tạo cùng lúc với class.
fun main(args: Array<String>) {
println("Hello!\nThis an example of accessing class variable without creating object.${MyClass.staticField}\n")
println("Hello!\nThis an example of accessing class Method without creating an object.${MyClass.getStaticFunction()}\n")
}
class MyClass {
companion object {
val staticField = "This is a Static Variable."
fun getStaticFunction(): String {
return "This is a static Method."
}
}
}
Kết quả
Hello! This an example of accessing class variable without creating object. This is a Static Variable. Hello! This an example of accessing class Method without creating an object. This is a static Method.
Lưu ý: thành viên trong companion object mặc định là val (immutable). Nếu cần mutable, dùng var.
Cách 2: Object class + @JvmStatic
object class là singleton. Gắn @JvmStatic để Kotlin biên dịch thành static method/field cho Java interop.
fun main(args: Array<String>) {
println("Hello!\nThis an example of accessing a class variable without creating an object.${MyClass.staticField}\n")
println("Hello!\nThis an example of accessing a class Method without creating an object. ${MyClass.getStaticFunction()}\n")
}
object MyClass {
@JvmStatic
val staticField = "This is a Static Variable."
@JvmStatic
fun getStaticFunction(): String {
return "This is a Static Method."
}
}
Kết quả
Hello! This an example of accessing a class variable without creating an object. This is a Static Variable. Hello! This an example of accessing a class Method without creating an object. This is a Static Method.
Cả hai cách đều cho phép gọi MyClass.staticField và MyClass.getStaticFunction() mà không cần instance.