androidengineers.Book a session

Kotlin Basics and Syntax

Variables and Data Types

article15 minEasy

Choose types that express the data

A type determines the operations allowed on a value. Int and Long hold fixed-width integers, Double holds floating-point numbers, Boolean holds a truth value, and String holds text. Kotlin often infers a variable's type from its initializer, but inference does not change the value's meaning.

fun main() {
    val completed: Int = 3
    val total = 8
    val ratio = completed.toDouble() / total
    val elapsedMillis = 3_000_000_000L
    val finished = completed == total
    println("$ratio, $elapsedMillis, $finished")
}

The output begins with 0.375. Without toDouble(), dividing two integers produces an integer, so 3 / 8 is zero. Numeric conversions are explicit: an Int is not automatically assignable to a Long variable. Values outside a type's range can overflow; choosing Long postpones that boundary but does not eliminate it.

Exercise

Write a function that returns a completion percentage from two counts. Define what happens when the total is zero and when completed exceeds total. Verify 3/8, 0/8, and 8/8 produce 37.5, 0.0, and 100.0 percent.

Check: explain why converting the result of integer division to Double is too late.

Reference: Numbers

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Variables and Data Types | Kotlin Core Programming | Android Engineers