Getting started Kotlin - Examples and explanations

Overview

Getting started Kotlin

I'm learning Kotlin, so I have been updating it with examples and explanations about the language that I'm using at work.

Projects

Examples of projects using Kotlin:

File types

  • .kts Kotlin script
  • .kt Kotlin class

Variables

There are two ways to declare variables using Kotlin: val and var.

  • val is a constant
  • var for a variable whose value can change

Example: 01-variable.kts

It's possible use conditional statements to assign a value to variable:

35) { "The answer is close." } else { "The answer eludes me." }">
val answerString: String = if (count == 42) {
    "I have the answer."
} else if (count > 35) {
    "The answer is close."
} else {
    "The answer eludes me."
}

Functions

We must pass params with types and every function needs return type too.

fun sum(a: Int, b: Int): Int {
    return a + b
}

// or

fun sum(a: Int, b: Int) = a + b

Example: 02-functions.kts

Concat String and Variables

There are some ways to concatenate variables in a String

fun bestAnime(): String {
    return "Naruto"
}

print("Best Animes:" + bestAnime())
print("Best Animes: ${bestAnime()}")

Exception Handler

Example of Try-catch block for exception handling

try {
    val message = "Hello World! I love Digimon!"
    message.toInt()
} catch (exception: NumberFormatException) {
    // ...
}

Properties

Instead to use getters and setters we can use properties

  • Getter
class Pokemon(val name: String, val type: String) {
    val description: String
        get() = "Pokemon ${name} is ${type} type"
}
  • Setter
var power = 0.0
    set(value) {
        if (value > 0) {
            field = value
        }
    }

Example: 03-properties.kts

Enum

enum class Console {
    GBA,
    PLAYSTATION,
    XBOX,
    SWITCH,
    PC
}

Example: 04-enums.kts

Class

Creating a class using Enum

class Game(val name: String,
           val console: Console) {
    fun play(): String {
        return "You're playing $name on $console"
    }
}

Example: 05-classes.kt

Lists

There is some ways to create lists in Kotlin

= mutableMapOf(0 to 50, 1 to 50, 2 to 100) // Empty List var pokemons = arrayListOf()">
var digimons = mutableListOf("Agumon", "Tailmon", "Angemon")
var digimons = listOf("Agumon", "Tailmon", "Angemon")
val digimonPower: MutableMap<Int, Int> = mutableMapOf(0 to 50, 1 to 50, 2 to 100)

// Empty List
var pokemons = arrayListOf<String>()

When

When is similar Java Switch

fun getPrice(console: Console): Int =
    when (console) {
        Console.GBA -> 1000
        Console.PLAYSTATION -> 5299
        Console.SWITCH -> 2500
        Console.XBOX -> 4200
        Console.PC -> 5000
    }

Example: 06-when.kt

Maps

Example of how to iterate over a map

val binaryRepresentation = TreeMap<Char, String>()

for (c in 'A'..'F') {
    val binary = Integer.toBinaryString(c.toInt())
    binaryRepresentation[c] = binary
}

for ((letter, binary) in binaryRepresentation) {
    println("$letter - $binary")
}

Example: 08-interatingovermap.kt

In

It's possible to use "in" in a conditional

fun isLetter(c: Char) = c in 'a'..'z' || c in 'A'..'Z'
fun isNotDigit(c: Char) = c !in '0'..'9'

Example: 09-inoperation.kt

Mock

We can use Mockito, but the best lib to mock using kolint is Mockk

val car = mockk<Car>()

every { car.drive(Direction.NORTH) } returns Outcome.OK

car.drive(Direction.NORTH) // returns OK

verify { car.drive(Direction.NORTH) }

confirmVerified(car)

References


developed by Jean Jacques Barros

You might also like...
Full stack examples of how to use Hotwire JS in Kotlin services

hotwire-kt A collection of Kotlin examples using the Hotwire JS framework to build interactive web apps with a Kotlin Armeria server backend. Using Ho

Examples for using Kotlin at a basic level for Android application development.
Examples for using Kotlin at a basic level for Android application development.

Kotlin Android Jetpack Basics Ejemplos para usar Kotlin a nivel básico para el desarrollo de aplicaciones Android. Kotlin Android Jetpack Basics Acerc

A coding examples project about Kotlin Programming language. 🇰
A coding examples project about Kotlin Programming language. 🇰

Kotlin Tutorial 👨🏻‍💻 What is Kotlin ❓ Kotlin is a new programming language, developed by JetBrains. Jetbrains is a popular software development com

Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP)

Mockative Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP). Installation Mockative uses KSP to generate

Kotlin microservices with REST, and gRPC using BFF pattern. This repository contains backend services. Everything is dockerized and ready to
Kotlin microservices with REST, and gRPC using BFF pattern. This repository contains backend services. Everything is dockerized and ready to "Go" actually "Kotlin" :-)

Microservices Kotlin gRPC Deployed in EC2, Check it out! This repo contains microservices written in Kotlin with BFF pattern for performing CRUD opera

🎲 Kotlin Symbol Processor to auto-generate extensive sealed classes and interfaces for Android and Kotlin.
🎲 Kotlin Symbol Processor to auto-generate extensive sealed classes and interfaces for Android and Kotlin.

SealedX 🎲 Kotlin Symbol Processor to auto-generate extensive sealed classes and interfaces for Android and Kotlin. Why SealedX? SealedX generates ext

Repo: Programming problems with solutions in Kotlin to help avid Kotlin learners to get a strong hold on Kotlin programming.

Kotlin_practice_problems Repo: Programming problems with solutions in Kotlin to help avid Kotlin learners to get a strong hold on Kotlin programming.

Kotlin-oop - Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura.

Projeto React OOP Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura

Kotlin-koans - Kotlin Koans are a series of exercises to get you familiar with the Kotlin Syntax

kotlin-koans-edu Kotlin Koans are a series of exercises to get you familiar with

Owner
Jean Jacques Nascimento Barros
Software Engineer at @itau
Jean Jacques Nascimento Barros
Getting Started with the URL Shortener project

Getting Started with the URL Shortener project Overall structure The structure of this project is heavily influenced by the clean architecture: A core

null 0 Nov 8, 2021
Spring-graphql-getting-started - Spring for GraphQL provides support for Spring applications built on GraphQL Java

Getting Started with GraphQL and Spring Boot Spring for GraphQL provides support

Shinya 0 Feb 2, 2022
This is a template to help you get started building amazing Kotlin applications and libraries.

Welcome to the Starter This is a template to help you get started building amazing Kotlin applications and libraries. Over time, examples will be comp

Backbone 8 Nov 4, 2022
This is a skeleton project for Zircon users that can be used to get started with Zircon.

Zircon Kotlin Skeleton Project This is a skeleton project for Zircon users that can be used to get started with Zircon. Getting started This project w

Vladislav Kashchey 0 May 3, 2022
Solution code for Android Kotlin Fundamentals Codelab 8.1 Getting data from the internet

MarsRealEstateNetwork - Solution Code Solution code for Android Kotlin Fundamentals Codelab 8.1 Getting data from the internet Introduction MarsRealEs

DavidHieselmayr 1 Apr 7, 2022
It is a project that contains lessons and examples about Kotlin programming language. 🇰

Kotlin Tutorials What is Kotlin? I added the platforms it supports and great resources. You can access the article from the link below: https://medium

Halil Özel 94 Dec 22, 2022
Kotlin Examples Problems

Kotlin Examples Problems --->>> Repo: Getting Started Kotlin <<<--- --->>> Repo Kotlin Koans <<<--- --->>> Repo: GameBoy Emulator Enviroment <<<--- --

Victor Bolinches 22 Oct 3, 2022
Kotlin Unit Testing Examples

Kotlin Unit Testing Examples Table of Contents Application Gradle, Kotlin & Groovy Junit4 Junit5 KotlinTest Spek Mockito Mockito-Kotlin Mockk Strikt T

Jarosław 110 Dec 11, 2022
kotlin koans examples

Kotlin Koans Build --->>> Repo: Getting Started Kotlin <<<--- --->>> Repo: Problems Kotlin <<<--- --->>> Repo: GameBoy Emulator Enviroment <<<--- --->

Victor Bolinches 121 Oct 3, 2022
101 examples for Kotlin Programming language.

This is a collection of runnable console applications that highlights the features of Kotlin programming language. The use of console application enab

Dody Gunawinata 192 Dec 1, 2022