Kotlin Syntax & Language Basics
Estimated reading: 3 minutes 30 views

🔒 Kotlin – Constants & Literals: Define Fixed Values in Your Code

🧲 Introduction – Why Learn Kotlin Constants & Literals?

In Kotlin, constants and literals help you define fixed, unchangeable values directly in your code. Constants improve readability, minimize errors, and support maintainability—especially when values are reused multiple times. Kotlin provides const val for compile-time constants and various types of literals for representing data.

🎯 In this guide, you’ll learn:

  • The difference between constants and variables
  • How to declare constants using const val
  • Various types of Kotlin literals (numeric, string, char, boolean, etc.)
  • Best practices for working with fixed values

🔐 Kotlin Constants – const val

Use const val to define compile-time constants that never change and are accessible globally.

✅ Syntax:

const val PI = 3.14159
const val APP_NAME = "KotlinApp"

🔍 Rules:

RuleDescription
Must be declared at top level or inside object
Can only hold primitive types or strings
Evaluated at compile-time

✅ Example:

object Config {
    const val TIMEOUT = 5000
}

fun main() {
    println("Timeout: ${Config.TIMEOUT}")
}

🟢 Output:

Timeout: 5000

📄 Difference: val vs const val

Featurevalconst val
MutabilityImmutableImmutable
Evaluation TimeRuntimeCompile-time
Allowed TypesAnyPrimitives & Strings only
ScopeAnywhereTop-level or inside object/companion
Use CaseDynamic valuesFixed, reusable constants

🔢 Kotlin Literals – Fixed Values in Code

Literals are hardcoded values written directly into your Kotlin code.

1️⃣ Integer Literals

val x = 100
val hex = 0xFF      // Hexadecimal (255)
val binary = 0b1010 // Binary (10)

2️⃣ Floating-Point Literals

val pi = 3.14        // Double by default
val g: Float = 9.8F  // Float with 'F' suffix

3️⃣ Boolean Literals

val isKotlinFun = true
val isOver = false

4️⃣ Character Literals

val grade = 'A'
val newline = '\n'

Special characters use escape sequences like:

  • \n – newline
  • \t – tab
  • \' – single quote
  • \\ – backslash

5️⃣ String Literals

val name = "Kotlin"
val multiline = """
    Kotlin supports
    multi-line strings
""".trimIndent()
  • Double quotes " for strings
  • Triple quotes """ for multiline text

6️⃣ Null Literals

val user: String? = null

Use null with nullable types (String?, Int?, etc.)


🚫 Common Mistakes

❌ Mistake✅ Correction
Using const val inside a functionOnly allowed at top-level or in object
Assigning runtime value to constUse val instead
Using non-primitive in const valOnly primitives and strings allowed

✅ Best Practices for Constants & Literals

PracticeReason
Use const val for unchanging global valuesAvoids magic numbers & duplication
Group constants inside object or companion objectOrganized and accessible
Prefer val for runtime constantsEnsures immutability at runtime
Avoid hardcoded values in logicReplace with named constants for clarity

📌 Summary – Recap & Next Steps

Constants and literals are essential for managing fixed values in your Kotlin programs. Use const val for compile-time constants and understand Kotlin’s literal types for numbers, strings, characters, and booleans.

🔍 Key Takeaways:

  • Use const val for compile-time constants (only top-level or object).
  • Literals represent hardcoded values like 123, 'A', "Hello", true.
  • Kotlin supports numeric, string, char, boolean, and null literals.
  • Always prefer named constants over magic numbers.

⚙️ Practical Use:
Helpful in defining API URLs, timeout durations, configuration flags, default messages, or fixed mathematical values in Android and server-side Kotlin applications.


❓ FAQs – Kotlin Constants & Literals

What is const val in Kotlin?
✅ A const val is a compile-time constant. It must be a primitive type or String and declared at the top level or inside an object.


Can I declare const val inside a function?
✅ No. const val can only be declared at the top level, inside object, or inside companion object.


What types are allowed in const val?
✅ Only primitives (Int, Float, Boolean, etc.) and String.


How do multiline string literals work in Kotlin?
✅ Use triple quotes """ for multiline strings. Use .trimIndent() to clean up indentation.


What’s the difference between a literal and a constant?
✅ A literal is a raw value (e.g., 42, "Hi") used directly. A constant is a named, reusable reference to such values (e.g., const val PI = 3.14).


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Kotlin – Constants & Literals

Or Copy Link

CONTENTS
Scroll to Top