Kotlin, with its being made as an officially supported language for Android development, has started to gain a lot of momentum among developers due to its numerous advantages over Java.

Fortunately, it’s similarity to Java makes it easy for those already comfortable with Java to plunge right in.

Running your programs

To quickly try your hand creating Kotlin programs, you can take advantage of Kotlin Playground, JetBrains’s online editor that allows you to edit and run programs in your browser.

Once you’re decent enough at it, you can directly create Android apps using Kotlin with Android Studio or through the free community version of IntelliJ IDEA.

The main method

Unlike Java, files don’t necessarily have to have their code encapsulated in a class with the same name as the file. The code below shows the entry point for Kotlin, a replacement for Java’s glorious “public static void main”:

// The args: Array<string> is optional fun main(args: Array<String>) { // println is the new System.out.println() // Note: Kotlin doesn't require semicolons println("Here's the infamous Hello World!") }

Variables

One thing to note here. val creates immutable variables whose values can’t be reassigned while var creates mutable variables like those in Java.

// These values are like constants: can't be reassigned val anInt: Int = 1234 val aFloat: Float = 100.00f val aDouble: Double = 123.00 val aLong: Long = 1000000004 val aShort: Short = 10 val aByte: Byte = 1 val aBool: Boolean = false // If your declaring and initializing it, you don't need to specify the type val aVal = 213.4 // If your not initializing it, you must specify the type val aString: String aString = "hi" // These are like the traditional variables: can be reassigned var x = 5 x++

Control flow

For if-else expressions, curly braces can be used, but are not needed if the code statement is only one line.

// In Kotlin, if statements return a value as Kotlin is a functional language val max = if (value1 > value2) value1 else value2 if(value1 > value2) { println("Value1 is bigger") } else if(value2 > value1) { println("Value2 is bigger") } else { println("They're the same!") }

As to switches, Kotlin uses when statements like so:

when (value) { 5 -> print("it's 5") 10 -> print("it's 10") else -> { // Note the block print("it's not 5 or 10") }

Arrays

Like variables, you do not need to specify what the data type of the members will be.

In addition, besides the traditional method of accessing the element through double square brackets, you can also use get() and set().

val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5) val names = arrayOf("Bob", "Bill", "Jack", "Jill", "Joe") // Kotlin supports arrays of mixed data types val randomArray = arrayOf(1, 2.3f, "Hello World", false) randomArray.set(2, "Bonjour le monde!") println("Hello world in french: " + randomArray.get(2) + " , it is completely " + randomArray[3])

Collections

There are two types: mutable and immutable (like lists, maps, and sets).

// Creates an immutable list val items = listOf(10, "hi", 30, 40) // Creates a mutuable list val mutuableList = mutableListOf(1, 2, 3) val immutableList:List<Int> = mutuableList // Can add elements to a mutuable list mutuableList.add(4) // ERROR: can't add elements to an immutable one immutableList.add(4)

Looping

If you’ve used Python before, Kotlin has a similar range function:

// Inclusive of both 0 and 10 for (i in 0..10) { print(i) } // Can also count down and adjust the step for (i in 10 downTo 0 step 2) { println(i) }

You can also loop through items in a collection or in an array.

for(i in items) println(i) // Loop using the indices as opposed to the elements for (i in array.indices) println(array[i])

While and do-while loops pretty much stay the same:

while(x > 0) { x-- } do { x-- println("Called once at least") } while (x > 0)

Note: break and continue can be used just like in Java

Functions

The fun keyword is used to indicate functions in Kotlin as you saw in fun main.

fun main(args: Array<String>) { // don't have to specify default values, but can println(message(10)) } // name followed by the type; can have default values after that fun message(age: Int, name: String = "Bob") : String { return "Hi, " + name + " . You are " + age } // single line functions do not need curly braces and 'return' can be replaced by an equals sign fun double(value: Int): Int = value * 2

Classes

There’s a lot of cool boiler-plate code saving things you can do in Kotlin.

For example, you could create a class this way:

fun main(args: Array<String>) { val newDog = Dog("Bob", 8) } // Creates a class Dog with a primary constructor class Dog constructor(_name: String, _age: Int) { // Initialize them without an init block var name: String = _name var age: Int = _age // Alternatively, you can initialize through an init block init { this.name = _name this.age = _age } }

Or, you can save all of that code and simply do the following:

// Creates a class Dog with a primary constructor class Dog constructor(var name: String, var age: Int) { init { println("A dog created: firstName = $name and lastName = $age") } }

The constructor keyword used here is used to indicate a primary constructor. In Kotlin, secondary constructors exist too, and more than one of them can be created. However, they all must call the primary constructor though this can be done indirectly through another secondary constructor:

// Creates a class Dog with a primary constructor class Dog constructor(var name: String, var age: Int) { // The ": this(name, age)" calls the primary constructor constructor(name: String, age: Int, dead: Boolean): this(name, age) { if(dead) this.age = 0 } }

Another cool thing about Kotlin is that getters and setters are automatically created. Using our previous Dog class and without adding any code, we can simply do the following:

var newDog = Dog("Bob", 8) println(newDog.name) // "Bob" println(++newDog.age) // 9

Adding methods to a class is simple enough, you can do so like this:

fun main(args: Array<String>) { var newDog = Dog("Bob", 8, false) newDog.bark() } class Dog : Animal { constructor(name: String, age: Int, dead: Boolean): super(name, age) { if(dead) this.age = 0 } fun bark() { println("Woof!") } }

Inheritance

In Kotlin, all classes by default are non inheritable; however, to mark them for inheritance, the open keyword needs to be used:

// Empty classes don't need braces open class Animal(var name: String, var age: Int) // Creates a class Dog with a primary constructor class Dog(name: String, age: Int) : Animal(name, age) { constructor(name: String, age: Int, dead: Boolean): this(name, age) { if(dead) this.age = 0 } }

If the child class does not have a primary constructor, then the secondary constructor must set up the parent through the super keyword.

// Creates a class Dog WITHOUT a primary constructor class Dog : Animal { // "super" is used to call to initialize the parent constructor(name: String, age: Int, dead: Boolean): super(name, age) { if(dead) this.age = 0 } }

Conclusion

If you’ve reached this far, and already knew Java, you’re pretty much set to start creating Kotlin programs. This article was by no means a complete tutorial to Java, but merely a concise quickstart for Java developers to try out this cool new language.

I feel that once you’ve learned this much as a programmer, you can pick up the rest through passive learning while working on your projects.

There’s no substitute for hands-on learning while creating your own programs (not to mention, searching Google — and Stack Overflow! — when you get stuck). And certainly, there’s no point bombarding you with all the tiny quirks and tidbits of Kotlin in one massive article.

After reaching here, feel like Kotlin is a viable replacement for Java? Do its advantages (such as significantly reducing the size of code files) outweigh the effort of learning a new language? Comment what you think down below!

Or if you have any questions or suggestions, also don’t hesitate to do so.

Until the next post!