ภาพรวม
ใน Kotlin ใช้คีย์เวิร์ด const ร่วมกับ val เพื่อประกาศค่าคงที่ (Compile-time Constant) ที่มีค่าไม่เปลี่ยนแปลงตลอดการทำงานของโปรแกรม
เงื่อนไขของ const val
- ต้องอยู่ที่ Top-level, Object Declaration, หรือ Companion Object
- Type ต้องเป็น Primitive Type หรือ String เท่านั้น
- ต้อง Initialize ด้วยค่าคงที่ (Constant Expression) - ไม่สามารถเรียก Function/Constructor ได้
- ไม่สามารถใช้กับ Local Variable ใน Function ได้
รูปแบบการประกาศ
1. Top-level Constant (แนะนำสำหรับ Global Constants)
// Constants.kt
const val APP_NAME = "MyApplication"
const val MAX_RETRY_COUNT = 3
const val API_BASE_URL = "https://api.example.com"
const val DEFAULT_TIMEOUT_MS = 5000L
fun main() {
println(APP_NAME) // MyApplication
}
2. Object Declaration (Singleton Constants)
object AppConfig {
const val VERSION = "1.0.0"
const val BUILD_NUMBER = 42
const val IS_DEBUG = true
}
fun main() {
println(AppConfig.VERSION) // 1.0.0
}
3. Companion Object (Class-scoped Constants)
class UserManager {
companion object {
const val DEFAULT_ROLE = "GUEST"
const val MAX_LOGIN_ATTEMPTS = 5
}
}
fun main() {
println(UserManager.DEFAULT_ROLE) // GUEST
}
4. Local Constant (val - ไม่ใช่ const)
fun process() {
// ไม่สามารถใช้ const ได้ใน Local Scope
val LOCAL_CONST = "This is local read-only"
println(LOCAL_CONST)
}
const val vs val
| ลักษณะ | const val | val |
|---|---|---|
| Initialize Time | Compile-time | Runtime |
| Allowed Types | Primitive + String | Any Type |
| Function Call Init | ❌ ไม่ได้ | ✅ ได้ |
| Annotation Parameter | ✅ ได้ | ❌ ไม่ได้ |
| Location | Top-level, Object, Companion | Everywhere |
| Memory | Inlined (แทนค่าตรง Bytecode) | Allocated Normally |
ตัวอย่างที่ Error
// ❌ Error: Const 'MY_CONST' initializer should be a constant expression
const val MY_CONST = computeValue()
// ❌ Error: Const 'MY_CONST' must be of primitive type or String
const val MY_CONST = MyClass()
// ❌ Error: Const can only be used on top-level or in objects
fun foo() {
const val LOCAL = "error"
}
Best Practices
- ใช้ Top-level const สำหรับ Application-wide Constants
- ใช้ Object Declaration จัดกลุ่ม Constants ที่เกี่ยวข้อง (Namespace)
- ใช้ Companion Object สำหรับ Constants ที่ผูกกับ Class เฉพาะ
- ตั้งชื่อเป็น UPPER_SNAKE_CASE (Convention)
- หลีกเลี่ยง
const valใน Companion Object หากไม่จำเป็นสำหรับ Java Interop (Performance: สร้าง Getter/Setter)
Annotation Usage
const val API_VERSION = "v1"
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class ApiEndpoint(val version: String = API_VERSION) // ✅ OK
@ApiEndpoint // ใช้ค่า Default จาก const
fun callApi() { }