Kotlin Tutorial 2 — Basic Data Types
In this tutorial only the most common Kotlin data types will be covered. Kotlin is one of the very few programming languages to have non nullable data types built into its type system. Every data type in Kotlin is referenced based (not value based) and is a sub type of Any, which is equivalent to Python’s Object. Unlike Python Kotlin makes a distinction between a character and a string, has type inference (feature found in modern statically typed programming languages), and has more diverse numeric data types.
Data can be temporarily stored in memory as a variable (var), or unlike Python as a constant (val). Any variable or constant defined MUST be assigned a value (reference). Below is an example in the Kotlin REPL illustrating this:
Here is what it would look like using Atom:
Note that the above illustration is utilising type inference hence the data type doesn’t need to be explicitly specified. Specifying the data type comes after the variable or constant name as shown below:
The following data types will not be covered: Float, Long, Short, Byte. It is important to note that some data types are not part of the Kotlin language, but are instead part of the Kotlin standard library. Single line comments are prefixed with //. Multi line comments start with /* and end with */.
Numeric Types
One of the very first data types you will come across is Int (integer) which represents a 32 bit whole number. Since it is a reference type you can call certain functions off it like toString. Try the following in the Kotlin REPL:
Next common data type you will encounter is Double which represents a 64 bit decimal point number. Try the following in the Kotlin REPL:
String And Char Types
Kotlin has two types of strings (String type), an ordinary string and a raw string. Try the following in the Kotlin REPL:
Finally Char (character) represents a single character. Try the following in the Kotlin REPL:
Conclusion
That concludes this tutorial where you now have a basic understanding of the common Kotlin data types. Next tutorial will look at Kotlin’s operators (including operator overloading) in Kotlin Tutorial 3 — Basic Operators.
TOC
- Kotlin Tutorial 1 — Introduction
- Kotlin Tutorial 2 — Basic Data Types
- Kotlin Tutorial 3 — Basic Operators
- Kotlin Tutorial 4 — Handling Input And Output
- Kotlin Tutorial 5 — Basic Collections
- Kotlin Tutorial 6 — Control Flow
- Kotlin Tutorial 7 — Functions
- Kotlin Tutorial 8 — Modularity
- Kotlin Tutorial 9 — Using An IDE
- Kotlin Tutorial 10 — Classes
- Kotlin Tutorial 11 — Inheritance
- Kotlin Tutorial 12 — Encapsulation And Polymorphism
- Kotlin Tutorial 13 — Generics