Code Monkey home page Code Monkey logo

getting-started-kotlin's Introduction

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:

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

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

getting-started-kotlin's People

Contributors

jjeanjacques10 avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.