Technology

const kotlin คือ

const kotlin คอ
const kotlin คือ | SiamCafe Blog
2025-07-20· อ. บอม — SiamCafe.net· 10,063 คำ

const val ใน Kotlin

const val Kotlin Compile-time Constant Primitive String Top-level companion object Inline Annotation val var Best Practices

Keywordเวลากำหนดค่าเปลี่ยนค่าได้Typeที่ประกาศ
const valCompile-timeไม่ได้Primitive + StringTop-level object companion
valRuntimeไม่ได้ทุก Typeที่ไหนัก็ได้
varRuntimeได้ทุก Typeที่ไหนัก็ได้
lateinit varRuntime (ทีหลัง)ได้Non-null ClassClass Property
lazy valFirst Accessไม่ได้ทุก Typeที่ไหนัก็ได้

Usage Examples

# === const val Examples in Kotlin ===

# // Top-level const val
# const val APP_NAME = "MyApp"
# const val APP_VERSION = "2.1.0"
# const val MAX_RETRIES = 3
# const val API_BASE_URL = "https://api.example.com"
# const val PI = 3.14159265358979
# const val IS_DEBUG = false
#
# // companion object
# class NetworkService {
#     companion object {
#         const val TIMEOUT_MS = 30_000L
#         const val MAX_CONNECTIONS = 10
#         const val HEADER_AUTH = "Authorization"
#         const val HEADER_CONTENT = "Content-Type"
#         const val CONTENT_JSON = "application/json"
#     }
#
#     fun makeRequest() {
#         // ใช้ const val
#         val timeout = TIMEOUT_MS
#         val header = HEADER_AUTH
#     }
# }
#
# // object (Singleton)
# object DatabaseConfig {
#     const val HOST = "localhost"
#     const val PORT = 5432
#     const val NAME = "production_db"
#     const val MAX_POOL_SIZE = 20
#     const val IDLE_TIMEOUT_MS = 60_000L
# }
#
# // ใช้กับ Annotation
# const val DEPRECATION_MSG = "Use newFunction() instead"
#
# @Deprecated(DEPRECATION_MSG)
# fun oldFunction() { }

from dataclasses import dataclass

@dataclass
class ConstExample:
    location: str
    code: str
    valid: bool
    note: str

examples = [
    ConstExample("Top-level",
        'const val MAX = 100',
        True,
        "ใช้ได้ Top-level ประกาศนอก Class"),
    ConstExample("companion object",
        'class A { companion object { const val X = 5 } }',
        True,
        "ใช้ได้ ใน companion object"),
    ConstExample("object",
        'object Config { const val PORT = 8080 }',
        True,
        "ใช้ได้ ใน object (Singleton)"),
    ConstExample("Function call",
        'const val NOW = System.currentTimeMillis()',
        False,
        "ใช้ไม่ได้ ต้องเป็น Literal ไม่ใช่ Function call"),
    ConstExample("Inside function",
        'fun test() { const val X = 5 }',
        False,
        "ใช้ไม่ได้ ห้ามประกาศใน Function"),
    ConstExample("Class type",
        'const val LIST = listOf(1, 2, 3)',
        False,
        "ใช้ไม่ได้ ต้องเป็น Primitive/String เท่านั้น"),
]

print("=== const val Examples ===")
for e in examples:
    status = "OK" if e.valid else "ERROR"
    print(f"  [{status}] {e.location}: {e.code}")
    print(f"    {e.note}")

val vs const val vs var

# === Comparison ===

@dataclass
class KeywordComparison:
    keyword: str
    assign_time: str
    mutable: bool
    types: str
    inline: bool
    use_case: str

comparisons = [
    KeywordComparison("const val",
        "Compile-time",
        False,
        "Int Long Float Double Boolean Char String",
        True,
        "Config ค่าคงที่ที่รู้ตอนเขียน Code API URL Port Timeout"),
    KeywordComparison("val",
        "Runtime (once)",
        False,
        "ทุก Type (Class Collection Function result)",
        False,
        "ค่าที่คำนวณตอน Runtime เช่น timestamp query result"),
    KeywordComparison("var",
        "Runtime (any time)",
        True,
        "ทุก Type",
        False,
        "ค่าที่เปลี่ยนได้ counter state mutable list"),
    KeywordComparison("lateinit var",
        "Runtime (deferred)",
        True,
        "Non-null Class (ไม่ใช่ Primitive)",
        False,
        "Dependency Injection Android View Binding"),
    KeywordComparison("by lazy { }",
        "First Access (lazy)",
        False,
        "ทุก Type",
        False,
        "Heavy init ที่ไม่ต้องการตอนเริ่ม DB connection Expensive calc"),
]

print("=== Keyword Comparison ===")
for c in comparisons:
    mutable = "Mutable" if c.mutable else "Immutable"
    inline = "Inline" if c.inline else "No Inline"
    print(f"\n  [{c.keyword}] {c.assign_time} | {mutable} | {inline}")
    print(f"    Types: {c.types}")
    print(f"    Use: {c.use_case}")

Best Practices

# === Organization Best Practices ===

@dataclass
class BestPractice:
    practice: str
    good_example: str
    bad_example: str
    reason: str

practices = [
    BestPractice("UPPER_SNAKE_CASE naming",
        "const val MAX_RETRIES = 3",
        "const val maxRetries = 3",
        "Convention สำหรับ Constants ทุกภาษา"),
    BestPractice("Group ใน Object",
        "object Api { const val BASE_URL = '...' const val TIMEOUT = 30 }",
        "const val API_BASE_URL = '...' const val API_TIMEOUT = 30",
        "จัดกลุ่ม Related Constants อ่านง่าย"),
    BestPractice("Private visibility",
        "private const val INTERNAL_SECRET = 'xxx'",
        "const val INTERNAL_SECRET = 'xxx'",
        "จำกัด Scope เท่าที่จำเป็น"),
    BestPractice("No hardcoded secrets",
        "val apiKey = BuildConfig.API_KEY",
        "const val API_KEY = 'sk-actual-key-here'",
        "Secret ต้องอยู่ใน Environment/BuildConfig"),
    BestPractice("Replace Magic Numbers",
        "if (retries > MAX_RETRIES)",
        "if (retries > 3)",
        "อ่านง่าย แก้ง่าย ค้นหาง่าย"),
]

print("=== Best Practices ===")
for p in practices:
    print(f"\n  [{p.practice}]")
    print(f"    Good: {p.good_example}")
    print(f"    Bad: {p.bad_example}")
    print(f"    Why: {p.reason}")

เคล็ดลับ

const val คืออะไร

Compile-time Constant Kotlin Primitive String Top-level companion object Inline Annotation Literal Value ไม่เปลี่ยน ไม่ Function call

val vs const val ต่างกันอย่างไร

const val Compile-time Primitive Inline Annotation val Runtime ทุก Type No Inline var Mutable เปลี่ยนได้ lateinit lazy Deferred

ใช้ที่ไหนได้บ้าง

Top-level companion object object Singleton Annotation ไม่ได้ใน Function ไม่ได้ใน Class ตรง ไม่ได้ Class Type ต้อง Primitive String

Best Practices มีอะไร

UPPER_SNAKE_CASE Group Object Private Scope No Hardcode Secret BuildConfig Replace Magic Numbers Feature-based Organization

สรุป

const val Kotlin Compile-time Constant Primitive String Top-level companion object val var lateinit lazy Inline Annotation Best Practices

📖 บทความที่เกี่ยวข้อง

const javascript คืออ่านบทความ → Kotlin Ktor Security Hardening ป้องกันแฮกอ่านบทความ → Kotlin Ktor Cost Optimization ลดค่าใช้จ่ายอ่านบทความ → context kotlin คืออ่านบทความ → Kotlin Compose Multiplatform Tech Conference 2026อ่านบทความ →

📚 ดูบทความทั้งหมด →