1 (edited by Hrvoje 2017-09-03 21:52:21)

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:
[email protected] for (i in 1..4) {
[email protected] for (j in 1..2) {
println("i = $i; j = $j")
if (i == 2)
[email protected]
}
}
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:
[email protected] for (i in 1..5) {
for (j in 1..4) {
if (i == 3 || j == 2)
[email protected]
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.

Thumbs up +2

2

I'd like to point out that it's best if you learn Java alongside Kotlin. However, this does sound like a good language (I'm going to see if Eclipse supports it). For books that teach you Kotlin, I found here the following books:

Both are purchasable here and here. Their descriptions follow:
Kotlin in Action:

Summary
Kotlin in Action guides experienced Java developers from the language basics of Kotlin all the way through building applications to run on the JVM and Android devices.
About the Technology
Developers want to get work done—and the less hassle, the better. Coding with Kotlin means less hassle. The Kotlin programming language offers an expressive syntax, a strong intuitive type system, and great tooling support along with seamless interoperability with existing Java code, libraries, and frameworks. Kotlin can be compiled to Java bytecode, so you can use it everywhere Java is used, including Android. And with an effi cient compiler and a small standard library, Kotlin imposes virtually no runtime overhead.
About the Book
Kotlin in Action teaches you to use the Kotlin language for production-quality applications. Written for experienced Java developers, this example-rich book goes further than most language books, covering interesting topics like building DSLs with natural language syntax. The authors are core Kotlin developers, so you can trust that even the gnarly details are dead accurate.
What’s Inside
Functional programming on the JVM
Writing clean and idiomatic code
Combining Kotlin and Java
Domain-specific languages
About the Reader
This book is for experienced Java developers.
About the Authors
Dmitry Jemerov and Svetlana Isakova are core Kotlin developers at JetBrains.

Programming Kotlin:

Familiarize yourself with all of Kotlin's features with this in-depth guide
About This Book

  • Get a thorough introduction to Kotlin

  • Learn to use Java code alongside Kotlin without any hiccups

  • Get a complete overview of null safety, Generics, and many more interesting features

Who This Book Is For
The book is for existing Java developers who want to learn more about an alternative JVM language. If you want to see what Kotlin has to offer, this book is ideal for you.
What You Will Learn

  • Use new features to write structured and readable object-oriented code

  • Find out how to use lambdas and higher order functions to write clean, reusable, and simple code

  • Write unit tests and integrate Kotlin tests with Java code in a transitioning code base

  • Write real-world production code in Kotlin in the style of microservices

  • Leverage Kotlin's extensions to the Java collections library

  • Use destructuring expressions and find out how to write your own

  • Write code that avoids null pointer errors and see how Java-nullable code can integrate with features in a Kotlin codebase

  • Discover how to write functions in Kotlin, see the new features available, and extend existing libraries

  • Learn to write an algebraic data types and figure out when they should be used

In Detail
Kotlin has been making waves ever since it was open sourced by JetBrains in 2011; it has been praised by developers across the world and is already being adopted by companies. This book provides a detailed introduction to Kotlin that shows you all its features and will enable you to write Kotlin code to production.
We start with the basics: get you familiar with running Kotlin code, setting up, tools, and instructions that you can use to write basic programs. Next, we cover object oriented code: functions, lambdas, and properties - all while using Kotlin's new features.
Then, we move on to null safety aspects and type parameterization. We show you how to destructure expressions and even write your own. We also take you through important topics like testing, concurrency, microservices, and a whole lot more. By the end of this book you will be able to compose different services and build your own applications.
Style and approach
An easy to follow guide that covers the full set of features in Kotlin programming.
Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the code file.

Kotlin in Action is laid out as follows:

The book is divided into two parts. Part 1 explains how to get started using Kotlin together with existing libraries and APIs:

  • Chapter 1 talks about the key goals, values, and areas of application for Kotlin, and it shows you the possible ways to run Kotlin code.

  • Chapter 2 explains the essential elements of any Kotlin program, including control structures and variable and function declarations.

  • Chapter 3 goes into detail about how functions are declared in Kotlin and introduces the concept of extension functions and properties.

  • Chapter 4 is focused on class declarations and introduces the concepts of data classes and companion objects.

  • Chapter 5 introduces the use of lambdas in Kotlin and showcases a number of Kotlin standard library functions using lambdas.

  • Chapter 6 describes the Kotlin type system, with a particular focus on the topics of nullability and collections.

Part 2 teaches you how to build your own APIs and abstractions in Kotlin and covers some of the language’s deeper features:

  • Chapter 7 talks about the principle of conventions, which assigns special meaning to methods and properties with specific names, and it introduces the concept of delegated properties.

  • Chapter 8 shows how to declare higher-order functions—functions that take other functions and parameters or return them. It also introduces the concept of inline functions.

  • Chapter 9 is a deep dive into the topic of generics in Kotlin, starting with the basic syntax and going into more-advanced areas such as reified type parameters and variance.

  • Chapter 10 covers the use of annotations and reflection and is centered around JKid, a small, real-life JSON serialization library that makes heavy use of those concepts.

  • Chapter 11 introduces the concept of domain-specific languages, describes Kotlin’s tools for building them, and demonstrates many DSL examples.

There are also three appendices. Appendix A explains how to build Kotlin code with Gradle, Maven, and Ant. Appendix B focuses on writing documentation comments and generating API documentation for Kotlin modules. Appendix C is a guide for exploring the Kotlin ecosystem and finding the latest online information.
The book works best when you read it all the way through, but you’re also welcome to refer to individual chapters covering specific subjects you’re interested in and to follow the cross-references if you run into an unfamiliar concept.

Programming Kotlin is laid out like this:

Chapter 1, Getting Started with Kotlin, covers how to install Kotlin, the Jetbrains Intellij IDEA, and the Gradle build system. Once the setup of the tool chain is complete, the chapter shows how to write your first Kotlin program.
Chapter 2, Kotlin Basics, dives head first into the basics of Kotlin, including the basic types, basic syntax, and program control flow structures such as if statements, for loops, and while loops. The chapter concludes with Kotlin-specific additions such as when expressions and type inference.
Chapter 3, Object-Oriented Code in Kotlin, focuses on the object-orientated aspects of the language. It introduces classes, interfaces, objects and the relationship between them, subtypes, and polymorphism.
Chapter 4, Functions in Kotlin, shows that functions, also known as procedures or methods, are the basic building blocks of any language. This chapter covers the syntax for functions, including the Kotlin enhancements such as named parameters, default parameters, and function literals.
Chapter 5, Higher Order Functions and Functional Programming, focuses on the functional programming side of Kotlin, including closures--also known as lambdas--and function references. It further covers functional programming techniques such as partial application, function composition, and error accumulation.
Chapter 6, Properties, explains that properties work hand in hand with object-orientated programming to expose values on a class or object. This chapter covers how properties work, how the user can best make use of them, and also how they are represented in the bytecode.
Chapter 7, Null Safety, Reflection, and Annotations, explains that null safety is one of the main features that Kotlin provides, and the first part of this chapter covers in depth the whys and hows of null safety in Kotlin. The second part of the chapter introduces reflection--run time introspection of code--and how it can be used for meta programming with annotations.
Chapter 8, Generics, explains that generics, or parameterized types, are a key component of any advanced type system, and the type system in Kotlin is substantially more advanced than that available in Java. This chapter covers variance, the type system including the Nothing type, and algebraic data types.
Chapter 9, Data Classes, shows that immutability and boiler-plate free domain classes are a current hot topic, due to the way they facilitate more robust code and simplify concurrent programming. Kotlin has many features focused on this area, which it calls data classes.
Chapter 10, Collections, explains that collections are one of the most commonly used aspects of any standard library, and Java collections are no different. This chapter describes the enhancements that Kotlin has made to the JDK collections, including functional operations such as map, fold, and filter.
Chapter 11, Testing in Kotlin, explains that one of the gateways into any new language is using it as a language for writing test code. This chapter shows how the exciting test framework KotlinTest can be used to write expressive, human-readable tests, with much more power than the standard jUnit tests allow.
Chapter 12, Microservices in Kotlin, shows that microservices have come to dominate server-side architecture in recent years, and Kotlin is an excellent choice for writing such services. This chapter introduces the Lagom microservice framework and shows how it can be used to great effect with Kotlin.
Chapter 13, Concurrency, explains that as multi-core aware programs are becoming more and more important in server-side platforms, This chapter is focused on a solid introduction to concurrent programming techniques that are vital in modern development, including threads, concurrency primitives, and futures.

Enjoy reading, and have fun with Kotlin!

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.

Thumbs up

3

[wow]. Thanks a lot for sharing this. Sounds interesting...

Best regards SLJ.
If you like the post, then please give it a thumps up.
Feel free to contact me privately if you have something in mind. If you do so, then please send me a mail instead of using the private message on the forum, since I don't check those very often.
Happy gaming... :D

Thumbs up

4

looks a bit like the swift I've looked at. It also seems to have a lot of the same goals that Apple has when they introduced swift as a replacement for objective C. both are fixing lots of things in the prior languages while making the programming environment safer and generally easier to get up and running.

I don’t believe in fighting unnecessarily.  But if something is worth fighting for, then its always a fight worth winning.
check me out on Twitter and on GitHub

Thumbs up

5

I've never used Swift, but may be. But Jetbrains's goal with Kotlin is targeting all platforms, including web and game development, which is cool.

Thumbs up

6

The bad thing about Swift is that Apple has not even comprehended making Swift available for Windows, Android, etc. They've only done it for Mac OS X and Linux, and I suspect that they only did it for Linux because people demanded that thy do so.

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.

Thumbs up

7

well, swift is open source so if swift is something you really want on windows or android get coding. I think its only a matter of time before it happens anyway.

I don’t believe in fighting unnecessarily.  But if something is worth fighting for, then its always a fight worth winning.
check me out on Twitter and on GitHub

Thumbs up

8

Point taken. I think it's been done before, although the binaries produced were... less than satisfactory, shall we say. RemObjects has also made Swift available for Windows, but they've done it in a proprietorial solution, and the way they've done it isn't the swift Apple made. Well, OK, it is, but it has several modifications to the language that make it possible to interface with the .NET, Coco, Java and Island platforms. (Island is RemObjects' native CPU compiler.)

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.

Thumbs up

9

Kotlin is open source too, I think they're using Apache license. BTW, a native compiler (for compiling into machine code rather than bytecode) development version is available for download on their website for Windows, Linux and Mac, and I'm looking forward to try it soon. I'll share my results. As I said, haven't tried Swift, so I can't say which one has more features and better code readability, but Kotlin had it enough to bring my attention, especially for Android development (if compared to Java). I don't say it's best, because there's no best programming language, but it's certainly something new and modern for this age. Some of the features that I like are: Kotlin lambdas, inline functions, function extensions that allow you to extend anything you want including built-in classes and types, data classes that will automatically generate geters and setters for you, various ways to handle nullables to avoid null pointer exceptions, singleton classes creation with object keyward, sealed classes that are better variant of enum classes, string templates, Kotlin Android extensions, the easy to use when statement, single-line functions, generics or labeled break/continue/loop statements. Of course many of these features are available in other languages, but Kotlin makes it more interesting and easy rather than tedious. I'll show more in upcoming posts.

Thumbs up

10

I'd love it if they added a match statement like F# has. In F# you could do something like:

let find filename str =
// ...
  match str with
    | str -> ln
    | _ -> 0
  0

We have the when statement, true; but it doesn't give you the absolutely full power of pattern matching, with regular expressions and such.

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.

Thumbs up