Kotlin Basics

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.

kotlin-basics-magda-miu

📌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.


// 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

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

📌Types in Kotlin

In Kotlin everything is an object, so at the language level we don’t have primitives.


// 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"

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

Arrays in Kotlin are represented using the Array class. To create an array we can use the helper function arrayOf() or the constructor Array()


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

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

String interpolation

  • Simple reference uses $
  • Complex references uses ${}
  • Raw Strings ”””


val firstWord = "Learn "
val secondWord = "Kotlin"
var bothWords = "$firstWord $secondWord"
println("$bothWords has ${bothWords.length}")
println(""""$bothWords" has ${bothWords.length}""")

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

📌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.
if/else


val number = 0
val result = if (number > 0) {
"Positive number"
} else if (number < 0) {
"Negative number"
} else {
"Zero"
}
println(result) // => Zero

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

when


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

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

when with range


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

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

when with check type


var sum = 234
when (sum) {
is Int -> println("The sum is $sum")
else -> println("It is not an Int")
}// => The sum is 234

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

for


for (index in 1..10) {
println(index)
}
for (index in 12 downTo 0 step 2) {
println(index)
}

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

for with index


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])
}

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

while and do…while


while (sumOfNumbers > 0) {
sumOfNumbers
}
do {
val result = retrieveData()
} while (result != null)

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

📌Equality checks

  • In Kotlin we have structural equality (a check for equals()==
  • Referential equality (two references point to the same object) ===


val countries = setOf("Java", "JavaScript", "Swift")
val neighbors = setOf("Swift", "JavaScript", "Java")
println(countries == neighbors) // => true
println(countries === neighbors) // => false

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

📌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


// 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

view raw

KotlinBasics.kt

hosted with ❤ by GitHub

Enjoy and feel free to leave a comment if something is not clear or if you have questions. And if you like it please like and share !

Thank you for reading! 🙌🙏😍✌

Follow me on:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s