Basics

San Skulrattanakulchai

September 19, 2018

Topics

Types

Literals, integer literals

Floating-point literals

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

Writable variables

Expressions

Type conversion

Function calls

Input/Output Functions

The ‘kotlin.math’ class

Generating random numbers

/*
 * This program expects one command line argument n as a positive integer.
 * Firstly, it generates a random integer (in the range of Int) and prints it.
 * It then generates a random real in the range [0,1) and prints it.
 * Lastly, it generates a random integer between 0 and n-1 inclusive
 * and prints it.
 */
fun main(args: Array<String>) { 
    val randGen = java.util.Random()
    val n = args[0].toInt()

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

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

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