A quick start to Kotlin
Intro
Android development is now Kotlin first and Kotlin is also used for cross platform. Right now is a good time to get into Kotlin especially if you are an Android dev.
This is article is aimed at giving you a very brief idea of the language to get you started. I would highly suggest you to go through the resources I have linked at the bottom.
Table of content
- Variables
- Basic Types
- Nullability
- Functions
- Loops
- Classes and Interfaces
- Resources
Variables
There are two types of variables in Kotlin.
val
- read only, can be assigned only once
val helloWorld = "Hello World"
print(helloWorld)
> Hello World
If you try to assign a new value to val, it results in an error
val helloWorld = "Hello World"
helloWorld = "Something else"
print(helloWorld)
> error: val cannot be reassigned
> helloWorld = "Something else"
var
- variables that can be reassigned, change the value as many times as required.
var helloWorld = "Hello World"
helloWorld = "Something else"
> print(helloWorld)
> Something else
Declaring Variables
Kotlin is statically typed. There are two ways to declare variables:
- Define the variable with its data type. The template to define a variable this way would be
val/var variableName: DataType = Your Data
var helloWorld: String = "Hello World!"
- Assign value to the variable without specifying the data type. Kotlin recognizes the type of data being assigned and creates a variable of the same data type.
The examples above follow this particular way of creating variables.
var helloWorld: String = "Hello World!"
Basic Types
Now that you know how to create variables, let’s go over the basic types available to us in Kotlin. The following are the basic types in Kotlin.
- Numbers
- Character
- Booleans
- Arrays
- Strings
Numbers
Numbers of all ranges and floating point numbers exist in Kotlin
val byte: Byte = 127 // Byte
val short: Short = 32767 // Short
val int: Int = 2_147_483_647 // Int
val long: Long = 9_223_372_036_854_775_807 // Long
The underscores you see in the numbers make no change to the number, they are treated as if they make numbers more readable but don’t change it’s value for example 1_000 == 1000
.
val float: Float = 1.1 // Float
val double: Double = 1.4444444 // Double
Character
Characters are in single quotes and Strings are in double.
You cannot have multiple characters in your character literal, for example if you declare a Char variable with multiple characters you get an error
val hello = 'Hello'
> error: too many characters in a character literal ''Hello''
> val hello = 'Hello'
Hence there exists strings, the same line of code works if we surround Hello
with double quotes instead of single quotes like we did earlier.
val hello = "Hello"
Booleans
You have true
and false
just like any other language as our booleans.
The following boolean operations are also available to us:
||
: OR&&
: AND!
: NOT/NEGATION
Arrays and Lists
Arrays in Kotlin have a fixed size, but come with some useful methods with them. You can use mutable lists if you need a collection where you can add and delete.
Once created we cannot add or remove elements from an array, only change their values.
Kotlin also has arrays of primitive types without boxing overhead: ByteArray, ShortArray, IntArray and so on. These classes have no inheritance relation to the Array class, but they have the same set of methods and properties.
// Creates an Array<Int> with values [0, 1, 2, 3, 4]
val nums = Array(5) { i -> i }
nums.forEach { println(it) }
// Array of int of size 5 with values [0, 0, 0, 0, 0]
val arr = IntArray(5)
Lists are similar to Arrays, there are two types of lists
- List: non-mutable
- MutableList: mutable
val numbers = listOf(1, 2, 3, 4)
val mutableNumbers = mutableListOf(1, 2, 3, 4)
The methods that comes with the list can be found here.
One of the main differences a List
and an Array
would be that values in the arrays can be changed, while values in the list cannot be changed since lists are not mutable.
Another one would be that Lists can have different implementation while Arrays are always sequential.
MutableLists are the way to go if you want a list with variable size. The methods that comes with the mutableList can be found here.
String
Strings like many other languages are surrounded by double quotes.
val hello = "Hello"
val hello2: String = "Hello!"
for (c in hello) {
print(c)
}
String templates: You can add a variables/logic to a string in the following way. Anything inside the curly braces ${}
is considered code, you could add a variable or logic there.
val str = "Is a equal to b? ${"a" == "b"}"
print(str)
> Is a equal to b? false
val num = 3
val str = "Value of num is ${num}"
print(str)
> Value of num is 3
Nullability
Now that you know about variables and types, let’s discuss nullability in Kotlin.
Kotlin’s type system is aimed to eliminate NullPointerException
, meaning there are less chances for your code to throw NullPointerException
. I say less chances because NPE’s do exist in Kotlin and there are a few ways they can happen. Nevertheless this allows us to safely call methods and access properties on non-nullable variables without worrying about NullPointExceptions
.
In Kotlin variables by default cannot hold null. Variables that can hold null have a ?
in front of their type. For example:
var a: String? = null // Nullable String
var b: Int? = 4 // Nullable Int
If you assign null to a non-nullable variable it will result in a compilation error. You can read about the Elvis operator for easy null checks and the !! operator to get a NPE if a variable is null.
Functions
Functions are defined using the fun
keyword followed be function name with parameters and return type.
/**
Return nothing so we dont have
a return type here.
*/
fun echo(text: String){
print(text)
}
/**
Same function but returns a String instead.
*/
fun echo2(text: String) : String{
print(text)
return text
}
echo("test")
> test
The function parameters can also have a default value. For example
/**
Takes a string and prints it. Prints
Hello if no parameters are passed.
*/
fun echo(text: String = "Hello"){
print(text)
}
val a = echo2()
print(a)
> Hello // From inside the function
> Hello // Printing value of a
While calling a functions, you can use name of a parameter to assign values.
/**
Takes a string and prints it. Prints
Hello if no parameters are passed.
*/
fun echo(text: String = "Hello"){
print(text)
}
val a = echo2(text = "using name of the parameter to assign value")
> using name of the parameter to assign value // From inside the function
Loops
Before we go over loops let’s take a look at ranges in Kotlin.
A Range in Kotlin look like 1..10
, this range if looped over would go from 1 through 10. Ranges can be of different types Int
, Char
, etc. You can change how you progress through a range using step
keyword. Instead of moving forward by a single increment we can jump 3 places like in the code below.
// A for loop that prints 12345678910
for (i in 1..10){
print(i)
}
// A for loop that prints 14710
for (i in 1..10 step 3){
print(i)
}
For loop
Iterates through anything that provides an iterator.
// looping over a range
for (i in 1..10){
print(i)
}
// use downTo to traverse backwards
for (i in 10 downTo 1){
print(i)
}
// looping over an array
val arr = arrayOf(1,2,3,4,5)
for (i in arr) {
print(i)
}
// can use withIndex on iterables
for ((index, element) in (1..5).withIndex()){
println("$index, $element\n")
}
While loop
While loops have a standard syntax. while
keyword followed by a condition, the loop stops when the condition is no longer true.
var i = 10
while (i > 0) {
print(x)
x -= 1
}
Classes and Interfaces
Classes in Kotlin can be defined in multiple ways, let’s start with one with just properties.
class Book {
var title: String = "How to be an awesome developer"
var author: String = "Avin Sharma"
var pages: Int = 270
}
The same class with a constructor.
class Book(title: String = "How to be an awesome developer", author: String = "Avin Sharma", pages: Int = 270) {
var title: String = title
var author: String = author
var pages: Int = pages
}
A more compact way to define class the constructor, getters and setters are automatically created.
class Book(var title: String, var author: String, var pages: Int){
...
}
Properties within a class, or member variables, are public by default. A class can have one or more init
blocks. You can also create secondary constructors.
Interfaces in Kotlin are also easy to create and use.
interface BookInterface{
fun readBook()
}
class Book: BookInterface{
override fun readBook(){
...
}
}
Inheritance
You must mark a class as open to allow it to be subclassed. Similarly, you must mark properties and member variables as open, in order to override them in the subclass.
open class Book(var title: String, var author: String, var pages: Int){
...
}
// Subclassing Book
class AnotherBook(var genre: String): Book{
...
}
Learning Resources
I think Kotlin Koans are one of the best resources to get familiar with Kotlin along with their docs.
Another set of really good resources can be found on developer.android.com ranging from Kotlin basics to Android dev in Kotlin, I enjoyed going through Kotlin Bootcamp.
For everything else search engines are your friend.