Kotlin Basics

San Skulrattanakulchai

September 18, 2019

Topics

Types

Primitive types

Primitive VS reference types

Primitives and their wrapper types

Literals, integer literals

Integer literals, continued

Floating-point literals

Char literals

Char literals, continued

Escape Sequence Unicode Meaning
‘\b’ ‘\u0008’ backspace
‘\t’ ‘\u0009’ horizontal tab
‘\n’ ‘\u000a’ linefeed
‘\r’ ‘\u000d’ carriage return
‘\"’ ‘\u0022’ double quotation mark
‘\'’ ‘\u0027’ single quotation mark
‘\$’ ‘\u0024’ dollar sign
‘\\’ ‘\u005c’ backslash

String literals

Operators

Operator Precedence

Operator Associativity

Basic Types

Type Size in Bits Sample Operators Literals
Boolean unspecified &&   ||   ! true   false
Byte 8 +   \(-\)   *   /   %
Char 16 + ‘a’   ‘0’   ‘\\’
Short 16 +   \(-\)   *   /   %
Int 32 +   \(-\)   *   /   % 321   0x3A   0b11
Long 64 +   \(-\)   *   /   % 3L
Float 32 +   \(-\)   *   /   % 2F   14.2e23f
Double 64 +   \(-\)   *   /   % 3.21   14.2e23
String + “Hello”
Array []

String Type

Keywords

Identifiers

Variables and assignment

Variables, continued

Readonly variables

Read-write variables

Expressions

Type conversion

Function calls

Input/Output Functions

The ‘kotlin.math’ package

Processing command line arguments

Generating random numbers

Example program

/*
 * This program demonstrates how to process command line arguments, and shows
 * how to call some random number generating functions.
 * See
 *
 *    https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.random/-random/index.html
 *
 * for all possibilities.
 */

import kotlin.system.exitProcess
import kotlin.random.*

fun main(args: Array<String>) { 
    val lo : Int
    val hi : Int

    if (args.size != 2) {
        println("Please give me exactly two nonnegative integers as arguments.")
        exitProcess(1)
    }

    try {
        lo = args[0].toInt()
    }
    catch (e: NumberFormatException) {
        println("'${args[0]}' is not an integer.")
        exitProcess(2)
    }
    try {
        hi = args[1].toInt()
    }
    catch (e: NumberFormatException) {
        println("'${args[1]}' is not an integer.")
        exitProcess(2)
    }

    if (lo < 0 || lo > hi) {
        println("Please give me 2 nonnegative integers lo and hi, with lo <= hi.")
        exitProcess(3)
    }

    // a pseudo-random integer
    var k = Random.nextInt()
    println("Your random integer is: $k")

    // a pseudo-random integer between 0 and hi-1
    k = Random.nextInt(hi)
    println("Your random integer between 0 and ${hi-1} inclusive is: $k")

    // a pseudo-random integer between lo and hi
    k = Random.nextInt(lo..hi)
    println("Your random integer between $lo and $hi inclusive is: $k")

    // a pseudo-random real between 0.0 and 1.0
    val r = Random.nextDouble()
    println("Your random real number in [0, 1) is: $r")
}