Kotlin Fundamentals (part 1)
Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of its standard library depends on the Java Class Library, but type inference allows its syntax to be more concise.
Kotlin was introduced in Google I/O 2017 and it was officially announced as the preferred language for Android app developers on 7th May, Google I/O 2019.
This short presentation at Google I/0 2017 on Introduction to Kotlin gives us a good glimpse and overview of the language and its capabilities.
In this series - Getting Started with Kotlin, we will start with the basic Kotlin fundamentals, moving on to loops, classes, functions, and other higher-order concepts by experimenting them with real-world examples and problems.
This Part -1 will cover the basic fundamentals of Kotlin -
- Why Kotlin
- Variables in Kotlin
- Operators in Kotlin
- String templates
- Conditional Expressions
- Loops and Ranges
- Nullability (Elvis and Bang Bang Operator)
You can also find the source code of these examples at -
1) Why Kotlin
There are mainly 3 advantages that Kotlin provides.
a) Modern and Concise
As Java was released 20 years ago, each new version of Java has to be compatible with the previous one thus piling up all that legacy baggage, while Kotlin is newer, lighter, more concise and expressive language that lets you focus on expressing the idea properly and write less boilerplate code.
Let’s consider an example.
Suppose we need to make a data class Box that has 3 parameters - length, breadth and hieght.Java Code for defining the Data class Box will be -
public class Box { private int length; private int breadth; private int height; public int getLength() { return length; } public void setLength(int length) { this.length = length; } public int getBreadth() { return breadth; } public void setBreadth(int breadth) { this.breadth = breadth; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } }
The same data class in Kotlin would look like -
class Box { var length = 0 var breadth = 0 var height = 0 }
Amazing! Isn’t it? Well, that’s not all.
b) Interoperability
Kotlin is 100% interoperable with Java so you can easily use Kotlin in your existing applications. Both Kotlin and Java generate the same bytecode, so there's no fear that you're shipping something completely different with Kotlin. This also makes it possible to use all the existing Java libraries in your Kotlin project.
c) Safer Code
One of the major pitfalls in any programming language is that accessing a member of a null reference will result in a null reference exception.
Kotlin provides @Nullable and @NonNull type to help you avoid Null Pointer exceptions. What that basically means is the type system distinguishes between references that can hold null and those that can not. We will discuss them in detail later in this article.
2) Variables in Kotlin
Kotlin mainly provides 2 types of variables - var and val. Read-only local variables are defined using the keyword val i.e they can be assigned a value only once while variables assigned using var can be reassigned.
3) Operators in Kotlin
Operators are the same in Kotlin as in Java with the addition that Kotlin provides member/extension functions for them.
For example -
var c = 10 c += 1; // using operators // using extension functions c.plus(1) // (Arithmetic operators) c.minus(1) // (Arithmetic operators) c.unaryPlus() // used for +a (unary operator) c.inc() // used for a++ (Increment operator)
4) String Templates
A template expression starts with a dollar sign ($) and consists of either a simple name or an arbitrary expression in curly braces. String templates can shorten string expressions by reducing the need for explicit string concatenation.
Let’s see an example -
val hours = 3 val minutes = 15 val time = " Time is $hours hours and $minutes minutes"
You can also call methods in your string template using curly braces.
time = "${getConvertedTime(currentDuration)} / ${getConvertedTime(totalDuration)}"
5) Conditional Expressions
Like Java, Kotlin also uses if/else as conditionals statements, but it can also be used as an expression. Kotlin replaces switch condition with ‘when’ with many more capabilities.
Considering this example -
fun isNoon(hourOfDay: Int) = if (hourOfDay >= 12) true else false // if as expression val type = 12 when(type) { // properties of when 0 -> print("Type is 0") in 1 .. 10 -> println("Between 1 to 10") !in 10 .. 20 -> println("Not in 10 to 20") is Int -> println("Type is of Int Type") else -> println("Greater than 10") }
6) Loops and Ranges
Like Java, Kotlin also offers various loops with additional features.
a) For Loop
The basic syntax of For Loop remains the same as in Java. It iterates over anything that is iterable or anything that is itself an iterator.
For example -
val arrayList = arrayListOf<String>("a", "b", "c") for (element in arrayList) { print("$element ") }
We can also print through elements and index at the same time using withIndex() function.
for((index, element) in arrayList.withIndex()) { println("$index is $element") }
b) While/Do-While Loop
While and do-while loops are pretty same as of Java, but the condition for the loop must be an actual boolean expression -
var x = 0 while (x < arrayList.size) { print(arrayList[x]) x++; }
c) Repeat
Kotlin also offers repeat for iterating over elements. It will execute the given action n no of times. Internally repeat also uses the ‘for’ loop for execution.
repeat(5) { i -> println("We are on the ${i + 1}. loop iteration") }
d) Ranges in Kotlin
Loops offer various manipulations in ranges -
Using .. operator, the endpoint is included in the for loop and hence the code below will give IndexOutOfBoundsException as it will run from 0 to 3.
for(index in 0..arrayList.size) { print(arrayList[index] + ", ") }
Using until we can exclude the endpoint for the loop and now it will run from 0 to 2.
for(index in 0 until arrayList.size) { print(arrayList[index] + ", ") }
To print the list in decreasing order we can use downTo which is also inclusive of both the starting point and endpoint.
for(index in arrayList.size - 1 downTo 0) { print(arrayList[index] + ", ") }
Step control the increment in the loop.
for(index in 0 until arrayList.size step 2) { print(arrayList[index] + ", ") }
We can simply iterate over elements like -
for(element in 'd'..'m') { print("$element") }
7) Nullability in Kotlin
As we discussed above, Kotlin provides @NonNull and @Nullable types of references. In this example we have 2 variables hours( NonNull) and mins(Nullable). A list of operations performed on these variables explains how Kotlin ensures null safety.
Accessing any property of Nullable type would result in the error -
We can avoid this using the safe call to the property using ?. or !!. operators.
?. is called the safe call operator. What it does is it first evaluates mins, if it is not null then only evaluates mins.length.
print(mins?.length)
?: is called the Elvis operator. What it does is it first evaluates the statement/expression on its left, if it is not null makes it the result of the expression else executes the right side of the operator.
print(mins?.length ?: 0)
!! is called the Bang - Bang or Double bang Operator. It basically converts any value to a non-null type. It is generally used in a situation where we know the value is not null, but the compiler doesn't realize it and this often happens when we are interacting with our java code.
For example, if we want to decrement the length we get from the above expression, calling dec() function on it would result in an error -
Because we know length will always be non-null, we can use bang-bang operator on property length.
println(mins?.length!!.dec())
Conclusion
So, In this article, we learned about why and how we can use Kotlin in our existing/new projects. We saw some fundamental concepts and how Kotlin can easily make your code more efficient, more readable with lesser lines. Try experimenting more with these concepts with the already set up source code in my repo.
There is a lot more that we will cover in the next articles -
If you like this article, don’t forget to clap and to keep up-to-date with all my new articles, you can follow me and my publication on Medium.
Any feedback, suggestions are always welcomed and appreciated!
Link to original article -
Keep Learning!