Topic Overview and Actualization

Welcome to our lesson on Kotlin's basic data types. We'll delve into numbers, booleans, characters, strings, and arrays. Additionally, we'll explore how to declare these data types—either explicitly or implicitly. These fundamentals will empower you to create and manipulate data effectively in your Kotlin programs.

Understanding Numbers in Kotlin

In Kotlin, numbers are categorized by their memory sizes and value ranges. For integral numbers, the most popular types are Int and Long, requiring 4 and 8 bytes of memory, respectively. For numbers with decimal points, we have Float and Double: Float supports approximately seven decimal places, while Double can handle around 15. There are also less popular data types such as Short and Byte, but we will omit them for now.

Let's explore these number types in action:

val intNumber: Int = 300 // stores numbers from -2147483648 (-2^31) to 2147483647 (2^31 - 1)
val longNumber: Long = 100_000_000L // stores numbers from -9223372036854775808 (-2^63) to 9223372036854775807 (2^63 - 1)

/*
 * The 'F' suffix in '2.5F' explicitly marks the value as a Float. 
 * This is required because Kotlin defaults to Double for decimals. 
 * It ensures the compiler adheres to the specified Float type.
 */
val floatNumber: Float = 2.5F 

val doubleNumber: Double = 5.5

In long numbers, Kotlin enhances readability through the usage of underscores, as seen in 100_000_000.

Booleans, Characters, and Strings in Kotlin

The Boolean data type represents truth values as true or false. The Char data type, represented by Char, holds a single character, while String stores sequences of characters. Please note that Chars are defined using single quotes ('), and Strings are defined using double quotes (").

val isKotlinFun: Boolean = true
val letter: Char = 'K'
val hello: String = "Hello, Kotlin!"
Explicit and Implicit Type Declarations

In Kotlin, data types can be declared explicitly by specifying the type, or implicitly, by letting Kotlin's type inference mechanism determine the type. To specify the type of a variable explicitly, use the syntax: val <variableName>: <variableType> = <value>.

For example:

val explicitInt: Int = 239 // Explicitly declare data type as Int
val implicitInt = 239 // Implicitly declare data type as Int

val explicitLong: Long = 3_000_000_000 // Explicitly declare data type as Long
val implicitLong = 3_000_000_000 // Implicitly declare data type as Long
val anotherLong = 239L // 239 fits into Int type and Kotlin will infer its type as Int. To specify the Long value explicitly, append the suffix `L` to the value.

val explicitString: String = "Explicit" // Explicitly declare data type as String
val implicitString = "Implicit" // Kotlin infers type as String
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal