it

const Kotlin คือ — ค่าคงที่ใน Kotlin ฉบับสมบูรณ์

const Kotlin คือ — ค่าคงที่ใน Kotlin ฉบับสมบูรณ์

const val ใน Kotlin

const Kotlin คือ — ค่าคงที่ใน Kotlin ฉบับสมบูรณ์

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

เนื้อหาเกี่ยวข้อง — ทำความเข้าใจ ฟองสบ — ทุกสิ่งที่ต้องรู้ในปี 2026

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

const Kotlin คือ — ค่าคงที่ใน Kotlin ฉบับสมบูรณ์
# === 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: ใช้สำหรับค่าที่รู้ตอนเขียน Code เท่านั้น
  • val: ค่าที่คำนวณตอน Runtime แต่ไม่เปลี่ยน ใช้ val
  • UPPER_SNAKE: ตั้งชื่อ const val เป็น UPPER_SNAKE_CASE เสมอ
  • Object: รวม Constants ใน object จัดกลุ่มตาม Feature
  • Security: ห้าม Hardcode Secret ใน const val

const val คืออะไร

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

แนะนำเพิ่มเติม — XM Signal

เนื้อหาเกี่ยวข้อง — แนะนำให้อ่าน Object Detection DevOps Culture

เนื้อหาเกี่ยวข้อง — บทความที่เกี่ยวข้อง: Zipkin Tracing Capacity Planning

XM Legend · เทรดเดอร์ & ผู้สอน Forex 13 ปี

ผู้ก่อตั้ง SiamCafe ตั้งแต่ปี 1997 · เทรดเดอร์สาย Forex มากกว่า 13 ปี ได้รับการยกย่องเป็น XM Legend · แบ่งปันความรู้ Forex, ไอที, AI และการเทรด จากประสบการณ์จริงในตลาดจริง