In my previous article we discovered details about how Kotlin was designed, what is the philosophy behind this new programming language and how its popularity has grown over the past years.
In this article we’re going to continue with some basic concepts from Kotlin Wonderland like the available types, control flow instructions, equality checks and null safety.
📌Define variables (val vs var)
- val is immutable (read-only) and we can only assign a value to them exactly one time.
- var is mutable and can be reassigned.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// immediate assignment | |
val countOfEvenNumbers: Int = 10 | |
// `Int` type is inferred | |
var sumOfNumbers = 0 | |
// type required when no initializer is provided | |
var countOfPrimeNumbers: Int | |
// deferred assignment | |
countOfPrimeNumbers = 3 | |
countOfPrimeNumbers = 24 |
📌Types in Kotlin
In Kotlin everything is an object, so at the language level we don’t have primitives.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Kotlin Numeric Types Examples | |
val myByte: Byte = 10 | |
val myShort: Short = 125 | |
val myInt = 3000 | |
val myLong = 3000L // The suffix 'L' is used to specify a long value | |
val myFloat = 123.45f // The suffix 'f' or 'F' represents a Float | |
val myDouble = 321.05 | |
val hundredThousand = 100_000 | |
val oneMillion = 1_000_000 | |
val aTrueValue = true | |
val letterChar = 'K' | |
val digitChar = '1' | |
var basicKotlin = "Basic Kotlin" |
Arrays in Kotlin are represented using the Array class. To create an array we can use the helper function arrayOf() or the constructor Array()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var numbers = arrayOf(1, 2, 3, 4, 5) | |
var colors = arrayOf("red", "blue", "pink", "yellow") | |
// primitive arrays | |
val myCharArray = charArrayOf('K', 'O', 'T', 'L', 'I', 'N') // CharArray (corresponds to Java 'char[]') | |
val myIntArray = intArrayOf(1, 3, 5, 7, 9, 11) // IntArray (corresponds to Java 'int[]') | |
// Array constructor | |
val numbersArray = Array(8, { i -> i * 2 }) // 0 2 4 6 8 10 12 14 |
String interpolation
- Simple reference uses $
- Complex references uses ${}
- Raw Strings ”””
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val firstWord = "Learn " | |
val secondWord = "Kotlin" | |
var bothWords = "$firstWord $secondWord" | |
println("$bothWords has ${bothWords.length}") | |
println(""""$bothWords" has ${bothWords.length}""") | |
📌Control flow: if, when, for, while
- if — in Kotlin if is an expression, so it returns a value. There is no ternary operator.
- when — replaces “switch” from Java. We can also check a value for being or not in a specific range and we can also check if a variable is or not of a particular type.
- for — iterates through anything that provides an iterator. Can use the withIndex library function.
- while and do … while — same behavior like in Java.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val number = 0 | |
val result = if (number > 0) { | |
"Positive number" | |
} else if (number < 0) { | |
"Negative number" | |
} else { | |
"Zero" | |
} | |
println(result) // => Zero |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val firstValue = 6 | |
val secondValue = 3 | |
val operator = "/" | |
val resultOfOperation = when (operator) { | |
"+" -> firstValue + secondValue | |
"–" -> firstValue – secondValue | |
"*" -> firstValue * secondValue | |
"/" -> firstValue / secondValue | |
else -> "$operator operator is invalid." | |
} | |
println(resultOfOperation) // => 2 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var age = 22 | |
when (age) { | |
in 1..18 -> print("Age is in the range") | |
!in 18..110 -> print("Age is outside the range") | |
else -> print("None of the above") | |
} // => None of the above |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sum = 234 | |
when (sum) { | |
is Int -> println("The sum is $sum") | |
else -> println("It is not an Int") | |
}// => The sum is 234 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for (index in 1..10) { | |
println(index) | |
} | |
for (index in 12 downTo 0 step 2) { | |
println(index) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var languages = arrayOf("Java", "Kotlin", "Scala", "C#") | |
for (item in languages) | |
println(item) | |
var desserts = arrayOf("Cupcake", "Ice cream", "Eclair", "Pie") | |
for (item in desserts.indices) { | |
if (desserts[item].length > 4) | |
println(desserts[item]) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
while (sumOfNumbers > 0) { | |
sumOfNumbers— | |
} | |
do { | |
val result = retrieveData() | |
} while (result != null) |
📌Equality checks
- In Kotlin we have structural equality (a check for equals()) ==
- Referential equality (two references point to the same object) ===
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val countries = setOf("Java", "JavaScript", "Swift") | |
val neighbors = setOf("Swift", "JavaScript", "Java") | |
println(countries == neighbors) // => true | |
println(countries === neighbors) // => false |
📌Null safety
- In an effort to rid the world of NullPointerException, variable types in Kotlin don’t allow the assignment of null. 👼👼👼
- In order to use a variable that can be null, declare it nullable by adding ? at the end of its type.
But… 😥😥😥
The only possible causes of NPE’s may be:
- An explicit call to throw NullPointerException()
- Usage of the !! operator (not-null assertion operator)
- Some data inconsistency with regard to initialization
- Java inter-operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// check for null in conditions | |
val trainingName: String? = "Learn Kotlin in 45 minutes" | |
if (trainingName != null && trainingName.isNotEmpty()) { | |
print("String of length ${trainingName.length}") | |
} else { | |
print("Empty string") | |
} | |
val platform: String? = null | |
val language = "Kotlin" | |
println(platform?.length) // safe call | |
println(language.length) // unnecessary safe call | |
val lengthOfWord = platform!!.length // !! operator | |
val numberOfLetters: Int? = lengthOfWord as? Int // safe cast |