Basic types
Hello world
Basic types
Collections
Control flow
Functions
Classes
Null safety
Every variable and data structure in Kotlin has a data type. Data types are important because they tell the compiler what you are allowed to do with that variable or data structure. In other words, what functions and properties it has.
In the last chapter, Kotlin was able to tell in the previous example that customers has type: Int. Kotlin's ability to infer the data type is called type inference. customers is assigned an integer value. From this, Kotlin infers that customers has numerical data type: Int. As a result, the compiler knows that you can perform arithmetic operations with customers:
fun main() { //sampleStart var customers = 10 // Some customers leave the queue customers = 8 customers = customers + 3 // Example of addition: 11 customers += 7 // Example of addition: 18 customers -= 3 // Example of subtraction: 15 customers *= 2 // Example of multiplication: 30 customers /= 3 // Example of division: 10 println(customers) // 10 //sampleEnd }xxxxxxxxxxvar customers = 10// Some customers leave the queuecustomers = 8customers = customers + 3 // Example of addition: 11customers += 7 // Example of addition: 18customers -= 3 // Example of subtraction: 15customers *= 2 // Example of multiplication: 30customers /= 3 // Example of division: 10println(customers) // 10tip
+=,-=,*=,/=, and%=are augmented assignment operators. For more information, see Augmented assignments.
In total, Kotlin has the following basic types:
Category | Basic types |
|---|---|
Integers |
|
Unsigned integers |
|
Floating-point numbers |
|
Booleans |
|
Characters |
|
Strings |
|
For more information on basic types and their properties, see Basic types.
With this knowledge, you can declare variables and initialize them later. Kotlin can manage this as long as variables are initialized before the first read.
To declare a variable without initializing it, specify its type with :.
For example:
fun main() { //sampleStart // Variable declared without initialization val d: Int // Variable initialized d = 3 // Variable explicitly typed and initialized val e: String = "hello" // Variables can be read because they have been initialized println(d) // 3 println(e) // hello //sampleEnd }xxxxxxxxxx// Variable declared without initializationval d: Int// Variable initializedd = 3// Variable explicitly typed and initializedval e: String = "hello"// Variables can be read because they have been initializedprintln(d) // 3println(e) // helloNow that you know how to declare basic types, it's time to learn about collections.
Explicitly declare the correct type for each variable:
fun main() { val a = 1000 val b = "log message" val c = 3.14 val d = 100_000_000_000_000 val e = false val f = '\n' }xxxxxxxxxxfun main() { val a = 1000 val b = "log message" val c = 3.14 val d = 100_000_000_000_000 val e = false val f = '\n'}Example solution{...}
Thanks for your feedback!