Hello all,
Since I've heard about Kotlin when Google announced that they're now officially supporting it as an Android primary development language, I've decided to try it and start learning it's features, and also share my knowledge as I learn.
In short, Kotlin is a modern staticly typed programming language developed by Jetbrains company from Russia. They wanted something to be much easier than Java and to fix problems that Java has, such as null pointer exceptions and verbosity. It will make code much more readable, and you don't need to spend countless lines of code to achieve a simple thing.
So, Kotlin is in fact a language that currently runs in Java virtual machine, but they're now working on a native compiler as well, which means that we will be able to write cross-platform games with no need for any Java runtimes installed in an easy and modern language in a near future. Currently if you write games in Kotlin, your end users have to install JRE. But the plus is that you can make cross-platform games with no modifications, you can mix up Java and Kotlin code and call Java functions inside Kotlin, and even convert Java code to Kotlin code if you're working with IntelliJ or Android Studio IDE.
Unlike Java, Kotlin is also procedural, so it doesn't force you to write everything inside classes like Java does.
Why I've chose Kotlin? Well, in short because it's totally different from languages that I've used or learned so far. Long answer: Since the first time I've seriously picked up Kotlin, I've started loving it. It's different from Python, but it may be faster as well. It can be more compared to languages such as Swift or Scalar, because it borrows some of it's features. The first official release 1.1 was in 2016, Plus it's actively developed. Second, I've chose it because I think that now is a right time to learn it, especially because it's a new language and some companies will be probably switching to it, which means that there is a bigger chance for you to have a job or to have an advantage at work if you know coding in Kotlin nowadays. If you wanna make Android apps or games, then Kotlin is of even higher importance and interest for you now when it's officially supported by Google.
So, since I'm learning it, I wanna show you some of it's syntax as well as some of it's features that I like eventually.
1. Hello World
So, let's start with popular starter example:
fun main(args: Array<String>) {
println("Hello world!")
}
So, 'fun' is a keyword to declare a function. It's name should be main in order for compiler to know that it's the first one that is executed. You will notice soon that Kotlin reverses variable names and variable types, so args is a variable name, followed by a colon, followed by it's type which is array of strings. The println is a function that will display something on screen, and you even don't need to end lines with semicolon (it's optional)! And yep, Kotlin loves braces for code blocks too, rather than indentation (Python) or keywords (Basic).
Back to variables. You even don't have to declare a variable if you initialize it. Only uninitialized variables have to be declared. Kotlin compiler will determin which type of variable it is depending on it's contents.
And this leads us to the second part of a discussion.
2. Variables
In Kotlin, there are two types of variables, and Kotlin calls them mutable or immutable. Simply described, mutable variables are these that can be changed, while immutable are constants and they cannot be changed. Mutable variables are defined with 'var' keyword, while immutable with 'val' keyword.
Example:
var myAge = 30
val myName = "Hrvoje"
So, the variable that holds my age is mutable, because my age will probably change (unless I die), but I have no plans to change my name, so I made it immutable or constant how it's called in other languages.
As I said, if you initialize a variable, you don't have to declare it's type. Here Kotlin recognized that myAge is of type integer, and myName is a string. But if you don't initialize it immediately, you have to declare it like this:
var myAge: Int
val myName: String
myAge = 30
myName = "Hrvoje"
Of course, you can also both declare and define it, like this:
var myAge: Int = 30 // mutable
val myName: String = "Hrvoje" // immutable
Remember, in Kotlin, the type goes after the name rather than before the name like in C++, Java or BGT, so this may be confusing to you as it was to me when I first looked at Kotlin code.
Now, we come to the next thing that I like in Kotlin, which is string templates. Now, if I wanna let the world know about my name and my age, I can write it as follows:
println("My name is $myName, and I'm $myAge years old.")
Yeah, you don't have to close and reopen quotes to display variable contents separated by pluses or commas. You just use a dollar sign if you wish to insert a variable inside a string.
However, if you call a variable from a class or a function, or perform calculations inside a string, you have to enclose it in braces like this:
println("My name is ${person.name}, and I am ${person.name} years old.")
or
println("Next year, I will be ${myAge + 1} years old.")
There are more types of variables, but it's a short demonstration rather than a Kotlin course, so I'l just mention some of these frequent by writing examples:
var letter: Char
var heIsStupid: Boolean
val name: String
val id: Int
var regCode: Long
var distanceToHell: float
3. Making decisions
So, let's start with Kotlin expression and statement. Like with Python, you can make a simple decision like this:
val myAge = 30
val answer = if (myAge > 80) "You're quite old" else "You're still young"
println(answer)
But you can also write it like this:
val myAge = 30
if (myAge > 80) {
print("You're quite old now.")
} else {
print("You're still young.")
}
And now, here comes the example for else if blocks:
val myAge = 30
val answer = if (myAge > 20)
"You're an adult now."
else if (myAge < 20)
"You're a teenager or a kid."
else
"I don't know what to say."
println("$answer")
When statement:
In C++, Java and BGT we have a switch case statement. I like it, but writing repetitive break; break; break; to end each case is rather annoying for some developers. In Kotlin, we can even use when instead an if statement. Here is the first example:
val age = 30
when (age) {
1, 2, 3 -> println("You're still baby, since you're less than 4 years old, and you are between 1 and 3 years old.")
30 -> println("You are 30 now, so you are in your best part of your life!")
50, 70 -> println("You are between 50 and 70 years old.")
}
So, you can even specify a range in case with ints, which is cool.
BTW, the -> (dash followed by greater than symbol also known as the arrow symbol) in Kotlin indicates a Lambda expression. Lambdas are cool too, you probably used them in Python and they allow us to write an anonimous function, but it may be too advanced topic for some of you. They are used to avoid less lines of unnecessary code.
When example2 with ranges:
when (age) {
in 1..10 -> println("Your age is between 1 and 11.")
in 13..18 -> println("You're teenager, between 13 and 19 years old.")
}
You write ranges in Kotlin with double period (..). So range between 10 and 20 is written as 10..20. And what's similar to Python, the keyword 'in' is used if we need to specify a range from an if statement or a loop.
4. Loops
We all know what is a for loop right?
Let's see it in Kotlin:
for (i in 1..5) println(i)
So, in a single line you define a for loop which prints numbers from 1 to 5. Much simpler and more readable than: for(i = 1; i<6; i++)
Now, pay attention. If you wanna print backwards, if you say:
for (i in 5..1)
It will not work! It will compile, but nothing will be printed. So, in this case, you use 'downTo' keyword, and you have to say it like this:
for (i in 5 downTo 1) print(i)
You can also loop by step like this:
for (i in 1..4 step 2) print(i)
This prints: 1 3 5
for (i in 4 downTo 1 step 2) print(i)
This prints: 5 3 1
Now, if you wish to loop over a collection, you do it like this:
var languages = arrayOf("English", "Spanish", "German", "French")
for (language in languages)
println(language)
Kotlin has many types of collections, mutable and immutable, such as arrayOf, listOf, mapOf (maps are like dictionaries in Python or BGT), and some more.
Next example: Let's say we have two couples, but we only wanna write girls names and not boys names.
var couples = arrayOf("Maria", "John", "Anna", "George")
for (person in couple.indices) {
if (person%2 == 0)
println(couples[person])
}
This prints: Maria Anna
We can also display string character by character with for loop:
var text = "AUDIOGAMES"
for (i in text) {
println(i)
And now we have a while loop.
Example 1:
var i = 1
while (i <= 5) {
println("Counting... $i")
++i
}
Note, we increment a value by writing ++i, not i++.
And now we have a do-while loop as well: This example calculates sum of entered numbers until user types 0.
var sum: Int = 0
var input: String
do {
print("Enter a number: ")
input = readLine()!!
sum += input.toInt()
} while (input != "0")
println("sum = $sum")
Note: readLine is a function that waits for user input. The .toInt is a method that converts entered string into integer.
And now some examples with break and continue.
Example 1:
firstLoop@ for (i in 1..4) {
secondLoop@ for (j in 1..2) {
println("i = $i; j = $j")
if (i == 2)
break@firstLoop
}
}
The At symbol here indicates labeled break. I like this in Kotlin. If running multiple loops, you can label them, so you know which one you wanna break or continue. Here I've labeled them simply firstLoop and secondLoop. Labeling is optional and you can omit it.
And now an example for continue:
firstLoop@ for (i in 1..5) {
for (j in 1..4) {
if (i == 3 || j == 2)
continue@firstLoop
println("i = $i; j = $j")
}
}
5. Functions
Functions are defined with 'fun' keyword, as I said at the beginning. Let's see an example:
fun callMe() {
println("Thank you for calling me.")
println("I'm still here, how nice of you to call me!")
}
fun main(args: Array<String>) {
callMe()
println("And now I'm back from call.")
}
Yep, so, if a function doesn't return anything, you don't have to specify that it's void. In fact, in Kotlin it's not void, it's Unit. But it's optional to specify it as a return type. Remember, just like with veriables, function return type is coming after the declaration rather than before, and function parameters are also defined on that way.
Example with arguments: A function that takes 2 arguments of type double and returns an integer.
fun addNumbers(first: Double, second: Double): Int {
val sum = first + second
val sumInt = sum.toInt()
return sumInt
}
But we can write simple functions in a single line as well! Let's say that we need a function that receives two strings, name and surname, and then converts and returns them as a single string, with name and surname separated by a space.
fun main(args: Array<String>) {
println(getFullName("Hrvoje", "Katic"))
}
fun getFullName(first: String, last: String) = "$first $last"
So, in this case, even braces were not required.
If you wanna specify default arguments, you do it like this:
fun display(letter: Char = 'a', length: Int = 15)
}
And these are just a basics, but Kotlin has many more powerful features that make it stronger and easier such as extension functions that allow you to extend anything (even string classes or numbers) with no need to touch the class, data classes that allow you to store and retrieve data with minimal lines of code, lambdas that I already mentioned, delegates and generics etc. I am still learning too, so I'll write more tutorials as I learn, if enough interested. Yes, I haven't shown Object Oriented Programming, because I think it would be too much for a forum post.
With concepts that I've covered so far, I think you're ready to write a classic "guess a number" game for exercise, which requires only variables, ifs and while loops.
Now, how to compile run Kotlin code?
For Android, if you wish to have integrated Kotlin support, then you currently need to get Android Studio 3.0 which is now in Beta4 stage at the time of this writing. For stable version 2.3, Kotlin plugin needs to be installed and configured separately.
If you wanna use command line and your primary editor such as Notepad++, Edsharp or Windows Notepad, then Java Development Kit and Kotlin command line compiler are enough.
Add the folder with kotlinc compiler and java binaries to your path variable in Windows to invoke it easily.
Kotlin files end with .kt extension. To compile, you write for example:
kotlinc foo.kt -include-runtime -d foo.jar"
And to run:
java -jar foo.jar"
You will probably need to enable Java Access Bridge. The instructions are at Oracle's website.
Tip: I've added compile and run commands to my Notepad++ Run menu, and defined a shortcut so I can compile with Control+F5 and run with Control+F9. To do this, in Notepad++ press F5, then write command and tab to Save to define a shortcut. Here's what you need to write asuming that your environment variables are already set:
For compile:
kotlinc "$(FULL_CURRENT_PATH)" -include-runtime -d "$(CURRENT_DIRECTORY)\bin\$(NAME_PART).jar"
And for run:
java -jar "$(CURRENT_DIRECTORY)\bin\$(NAME_PART).jar"
And now important links:
Kotlin official site: https://kotlinlang.org/
Kotlin beginner tutorial: https://www.programiz.com/kotlin-programming
Kotlinc command line compiler (currently V1.1.4): https://github.com/JetBrains/kotlin/rel … -1.1.4.zip
Java JDK: http://www.oracle.com/technetwork/java/ … 33151.html
Thanks for reading. See you soon.