Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Hằng số (Constants) trong Kotlin và cách tạo

Giới thiệu

Mọi ngôn ngữ đều cần biến giá trị không đổi. Kotlin dùng từ khóa const để khai báo hằng số compile-time.

1. Khai báo top-level

Đặt đầu file, dùng toàn bộ file scope.

private const val MY_TOP_LEVEL_CONST_VAL = "Type 1--> Example of Top Level Constant Value"

fun main() {
    println(MY_TOP_LEVEL_CONST_VAL)
}

Kết quả: Type 1--> Example of Top Level Constant Value

2. Hằng số cục bộ (local constant)

Trong hàm, phạm vi block.

fun main() {
    val MY_LOCAL_CONST = "Type 2-->Example of local const value"
    println(MY_LOCAL_CONST)
}

Kết quả: Type 2-->Example of local const value

3. const trong companion object

Không khuyến khích do companion object sinh getter/setter mặc định, ảnh hưởng performance.

fun main() {
    println(Student.MY_CONSTANT)
}

class Student() {
    companion object {
        const val MY_CONSTANT = "Type 3--> Using companion Object"
    }
}

Kết quả: Type 3--> Using companion Object

4. Object declaration (singleton)

fun main() {
    println(MyConstant.Const_USING_OBJECT_CLASS)
}

object MyConstant {
    const val Const_USING_OBJECT_CLASS = "Type 4-->Example of const using object class"
}

Kết quả: Type 4-->Example of const using object class

Lưu ý: const chỉ dùng với kiểu nguyên thủy/String, khởi tạo compile-time. val dùng cho runtime constant.