From Junior to Master in Kotlin — 1 (Basic Syntax)

Gerardo Lopez Falcón
4 min readMay 12, 2021

--

Kotlin is a modern but already mature programming language aimed to make developers happier. It’s concise, safe, interoperable with Java and other languages, and provides many ways to reuse code between multiple platforms for productive programming.

I want to share some thoughts and experiences that I have and will have in my career using Kotlin. Do you want to become a great Android/Kotlin developer? Yes? Ok please follow me in this series named From Junior to Master in Kotlin.

This first post explains the basic syntax in Kotlin, enjoy it.

Program entry point

An entry point of a Kotlin application is the main function.

fun main() {
println("Pura vida, Costa Rica!")
}

Package definition and imports

Package specification should be at the top of the source file.

package my.puravida

import kotlin.text.*

// ...

Functions

A function with two Int parameters and Int return type.

fun calc(a: Int, b: Int): Int {
return a + b * 7
}

A function body can be an expression. Its return type is inferred.

fun calc(a: Int, b: Int) = a + b * 7

Print to the standard output

print prints its argument to the standard output.

print("Hello")
print(" I live in Costa Rica")

output

Hello I live in Costa Rica

println prints its arguments and adds a line break, so that the next thing you print appears on the next line.

println("Hello")
println("I live in Costa Rica")

output

Hello 
I live in Costa Rica

Variables

Read-only local variables are defined using the keyword val. They can be assigned a value only once.

val x: Int = 1  // immediate assignment
val y= 2 // `Int` type is inferred
val z: Int // Type required when no initializer is provided
z = 3 // deferred assignment

Variables that can be reassigned use the var keyword.

var falcon = 5 // `Int` type is inferred
falcon += 1

Creating classes and instances

To define a class, use the class keyword.

class Shape

Properties of a class can be listed in its declaration or body.

class Rectangle(var height: Double, var length: Double) {
var perimeter = (height + length) * 2
}

The default constructor with parameters listed in the class declaration is available automatically.

val rectangle = Rectangle(5.0, 2.0)println("The perimeter is ${rectangle.perimeter}")

Inheritance between classes is declared by a colon (: ). Classes are final by default; to make a class inheritable, mark it as open.

open class Shapeclass Rectangle(var height: Double, var length: Double): Shape() {
var perimeter = (height + length) * 2
}

String templates

var a = 1// simple name in template:val s1 = "a is $a"a = 2// arbitrary expression in template:val s2 = "${s1.replace("is", "was")}, but now is $a"

Comments

Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments.

// This is an end-of-line comment/* This is a block comment
on multiple lines. */

Block comments in Kotlin can be nested.

/* The comment starts here
/* contains a nested comment */
and ends here. */

or loop

val items = listOf("apple", "banana", "kiwifruit")for (item in items) {    println(item)}

or

val items = listOf("Inter", "Real Madrid", "Saprissa")for (index in items.indices) {  println("item at $index is ${items[index]}")}

Collections

Check if a collection contains an object using in the operator.

when {  "orange" in items -> println("juicy")  "apple" in items -> println("apple is fine too")}

Using lambda expressions to filter and map collections:

val fruits = listOf("banana", "avocado", "apple", "kiwifruit")fruits.filter { it.startsWith("a") }.sortedBy { it }.map { it.uppercase() }.forEach { println(it) }-------------------Result------------------
APPLE
AVOCADO

Nullable values and null checks

A reference must be explicitly marked as nullable when null a value is possible. Nullable type names have ? at the end.

Return null if str does not hold an integer:

fun parseInt(str: String): Int? {
// ...
}

Use a function returning a nullable value:

fun printProduct(arg1: String, arg2: String) {  val x = parseInt(arg1)  val y = parseInt(arg2)// Using `x * y` yields error because they may hold nulls.  if (x != null && y != null) {    // x and y are automatically cast to non-nullable after null check  
println(x * y)
} else { println("'$arg1' or '$arg2' is not a number")
}
}

or

// ...if (x == null) {  println("Wrong number format in arg1: '$arg1'")   return
}
if (y == null) { println("Wrong number format in arg2: '$arg2'") return
}
// x and y are automatically cast to non-nullable after null checkprintln(x * y)

Conditional expressions

fun maxOf(a: Int, b: Int): Int { if (a > b) {  return a
} else {
return b
}
}

In Kotlin, if can also be used as an expression.

fun maxOf(a: Int, b: Int) = if (a > b) a else b

I hope you could to learn the basic syntax of the Kotlin language. Keep you stunned, I will post more tips and tricks about Kotlin in the future soon, continue following me in this journey.

--

--

Gerardo Lopez Falcón
Gerardo Lopez Falcón

Written by Gerardo Lopez Falcón

Google Developer Expert & Sr Software Engineer & DevOps &. Soccer Fan