Algus

Basic Syntax

[[ Variables ]] ⇣

Use val for a variable whose value never changes.

⚠️ val isn’t a constant

// String type definition
val playerName: String = "Algus Dark"

// ✘ Val cannot be reassigned
playerName = "New Name" 

Use var for a variable whose value can change

// 💡 When you assign an initial value the Kotlin compiler 
// can infer the type based on the type of the assigned value.
var playerLevel = 2
playerLevel = 3

[[ Null safety ]] ⇣

Kotlin variables can’t hold null values by default. For a variable to hold a null value, it must be of a nullable type.

// ✘ Null can not be a value of a non-null type String
val playerName: String = null

// 💡 Adding `?` makes this a nullable type
val playerName: String? = null****

[[ Built-in Types ]] ⇣

A Type describes the data that is held by a variable or a constant and tells the compiler how type checking will be handled.

TypeDescriptionTypeDescription
String“Text”CharCharacter
Booleantrue | falseIntByte | Short | Int | Long
Float | DoubleDecimal NumberListCollection of elements
SetCollection of unique elementsMapCollection of key-value pairs

Java types

In Java, there are two kinds of types: reference types and primitive types.

The name of reference types in Java begins with a Capital letter to indicate that they are backed by a source definition. E.g. Integer.

The names of Java primitive types start with a lowercase letter. E.g. int.

All primitives in Java have a corresponding reference type, but not all reference types have a corresponding primitive type.

One reason for choosing a reference type is that there are certain features of the Java language that are only available when using reference types. Generics, for example, don’t work with primitives. Reference types can also work with the object-oriented features of Java than its primitive values.

On the other hand, primitives offer better performance and some other perks.

Unlike Java, Kotlin provides only one kind of type: reference types.

Kotlin made this design decision for several reasons:

[[ Compile-Time Constants ]] ⇣

There are special cases where a val can return different values (more on that later). When we are sure that a piece of data won’t be changed, we should use a compile-time constant.

💡 A const declaration gives the compiler the flexibility to perform optimization behind the scenes.

const val THE_ANSWER = 42

fun main(){
	println(theAnswer)
}