0
0
KotlinConceptBeginner · 3 min read

What is Long in Kotlin: Explanation and Usage

Long in Kotlin is a data type used to store whole numbers that are larger than what Int can hold. It represents a 64-bit signed integer, allowing you to work with very large or very small integer values.
⚙️

How It Works

Think of Long as a bigger container for numbers compared to Int. While Int can hold numbers roughly between -2 billion and 2 billion, Long can hold much larger numbers, from about -9 quintillion to 9 quintillion. This is because Long uses 64 bits of memory, doubling the size of Int which uses 32 bits.

Using Long is like having a bigger jar to store more marbles (numbers). When you expect your numbers to be very large, you choose Long to avoid running out of space and causing errors.

💻

Example

This example shows how to declare and use a Long variable in Kotlin. It prints the value and its type.

kotlin
fun main() {
    val bigNumber: Long = 9223372036854775807L
    println("Value: $bigNumber")
    println("Type: ${bigNumber::class.simpleName}")
}
Output
Value: 9223372036854775807 Type: Long
🎯

When to Use

Use Long when you need to store whole numbers that are too large for Int. For example, when working with timestamps in milliseconds, large counts, or financial calculations involving big numbers.

Choosing the right type helps your program run correctly and efficiently. If you use Int for very large numbers, you risk overflow errors where the number wraps around unexpectedly.

Key Points

  • Long stores 64-bit signed integers.
  • It can hold much larger values than Int.
  • Use it for large whole numbers like timestamps or big counts.
  • Declaring a Long requires the L suffix or explicit type.

Key Takeaways

Long is a 64-bit integer type for large whole numbers in Kotlin.
Use Long when Int is too small to hold your number.
Declare Long variables with an explicit type or an L suffix.
It helps avoid errors from number overflow in large integer calculations.