Types and Templates

Basic Types, Type Inference and String Templates

JavaScript has one number type, a 64-bit float. Kotlin has Byte, Short, Int and Long (8 to 64 bits), Float and Double, plus Boolean, Char (in single quotes) and String. The compiler infers them: a whole number is an Int unless it is too big for one, a decimal is a Double, and an f suffix makes a Float.

types.kt: inferred types, integer arithmetic and a string templateKotlin
fun main() {
    val values = listOf<Any>(312, 9_780_000_000_000, 14.99, 4.6f, true, 'Q', "Fiction")
    println(values.joinToString { "${it::class.simpleName}" })
    println("${7 / 2} ${7 / 2.0} ${Int.MAX_VALUE + 1} ${0.1 + 0.2}")
    val title = "Salt and Saffron"
    println("$title has ${title.length} letters and costs \$${"%.2f".format(24.0)}")
}
Output
Int, Long, Double, Float, Boolean, Char, String
3 3.5 -2147483648 0.30000000000000004
Salt and Saffron has 16 letters and costs $24.00

Line 4 holds the surprises: 7 / 2 truncates to 3, and Int arithmetic wraps silently at 2^31, where JavaScript prints 2147483648; floating point matches JavaScript exactly. Nor is there implicit widening: passing an Int variable where a Long is expected is an "argument type mismatch" until you call toLong(). Templates are template literals in double quotes ($name, ${expression}, \$ for a dollar sign), and "%.2f".format(x) replaces toFixed(2).