Kotlin 101

Introduction

This article is the reference guide for DSC Binus Internation - Android Workshop Series.

Kotlin is cross-platform, statically typed and general purpose programming language that is designed by Jetbrains to be compatible with JVM (even though it can also target other compilation target).

After Google annouce that kotlin has became the prefered language for Android development, it’s popularity has skyrocketed. as the result, more and more people are trying to learn kotlin.

In this article, I’m going to explain most of the kotlin basics that you need master to get started in Android development.

This article will not explain about how to use Kotlin with Android yet, that topic will be available in form of future articles.

Kotlin and IDE installation

This article is written with 1.4.10, for best experience please use this version.
This article is currently under development and will be updated later

For this article, we will be using kotlin and intellij.

Variable

Definition

A variable is a name referencing to a specific storage location inside the computer’s memory which store data/information referred as value.

Terms

Assigning vs Initializing a Variable

Assigning a variable is the same as setting or re-setting value into the memory. Initializing a variable on the other hand means creating a variable for the first time in the program as well as assigning a variable to it.

1
2
3
4
5
// Initialize a variable named 'initialization' and assign a String typed value 'light bear' into it
var initialization: String = "light bear"

// Re-assign a new value 'a new light bear' to 'initialization' variable
initialization = "a new light bear"

Syntax

Variable Initialization Syntax

The complete syntax of variable initialization is,

1
var name: String = "light bear"
  1. There are 2 keywords used in Kotlin to declare a variable, var or val. One of these keywords must appear in every variable declaration or initialization and located at the front. A var declares a mutable variable. On the other hand, a val declares an immutable variable which means once a value is assigned to the variable, that value is no longer can be re-assigned. In the syntax example above, the var keyword is used, so the value can be re-assigned later.

  2. The var keyword is followed by a variable name. That name is the reference to the value stored in the memory. Whenever we want to retrieve or update the stored data, we simply call that name.

    There are a few things to note when naming a variable:

    • It should be in alphabetical characters (‘a’ to ‘z’ and ‘A’ to ‘Z’).

    • It can contains number but not as a prefix.

      1
      2
      3
      4
      var 1name: String // Not Allowed

      var name1: String // Allowed
      var n1ame: String // Allowed
    • The only symbol allowed in variable name is underscore ‘_’. However, the underscore must be accompanied by at least one alphabetical character or number.

      1
      2
      3
      4
      5
      6
      7
      8
      var _: String // Not Allowed
      var __: String // Not Allowed
      var 1_: String // Not Allowed

      var _1: String // Allowed
      var _name: // Allowed
      var n_ame: // Allowed
      var name_: // Allowed
    • Variable naming in Kotlin is case sensitive, which means a capitalized ‘A’ is different with a lower cased ‘a’.

      1
      2
      3
      var name: String = "light bear"
      var NAME: String = "LIGHT BEAR" // Different from 'name' variable
      var Name: String = "Light Bear" // Different from 'NAME' and 'name' variable
    • Whitespaces must not exist between characters. Use snake case (each phrase separated by underscore ‘_’) or camel case (phrases separated by uppercase letter).

      1
      2
      3
      4
      5
      6
      7
      8
      // A whitespace exist between the word 'my' and 'name'
      var my name: String = "light bear" // Not Allowed

      // Using snake case
      var my_name: String = "light bear" // Allowed

      // Using camel case (recommended as accorded to convention)
      var myName: String = "light bear" // Allowed

      NOTE: According to Kotlin coding convention, “local variables starts with a lower case letter and use the camel case and no underscores.”. It is recommended for programmers to follow this rule for better distinction and ambiguity prevention.

  3. Then, the variable name is followed by a colon ‘:’ and the type of the variable. The variable type is optional in a variable initialization since Kotlin is able to specify automatically the variable type by the value provided (implicitly decide the type).

    1
    2
    3
    // Initialization without specifying its type
    // The type of this variable is clear, it can be seen from the data, which is a string.
    var name = "light bear" // Allowed
  4. Last but not least, is the assignment operator ‘=’ followed by a specified value. The function of the assignment operator is similar to how it sounds, it assigns the value on its right side to the variable name on its left side.

    It can also be read as “assigning value ‘light bear’ to ‘name’ variable” (set the value of variable named ‘name’ as ‘light bear’).

Access The Stored Value

The stored value can be accessed by calling the variable name.

1
2
var name: String = "light bear" // Initialize a variable
println(name) // Outputs 'light bear' in the console

When the code in the example above is run, the word ‘light bear’ will be printed in the console. The println() function[^1] is used to achieve that result. However, notice the variable named ‘name’ inside the parenthesis of println(). This is what it meant by calling a variable. The variable references a location inside the memory which contains the value ‘light bear’ and by calling that, the stored value will be retrieved and printed out by using println(). So, variable can also be said as the representation of the stored value, the println(name) can be said as println(“light bear”).

Update The Stored Value

To update the stored value or re-assign the variable with a new value, the variable name is called, followed by an assignment operator and the new value without declaring ‘var’ or ‘val’ nor re-specifying its type:

1
2
var name: String = "light bear" // Initialize a variable
name = "a new light bear" // Assign a new value 'a new light bear' to variable named 'name'

When re-assigning a variable, the type of the new value must match the type of variable specified during the initialization.

1
2
var name: String = "light bear" // Initialize a variable
name = 15 // Error, '15' is an integer

The value of variable which is declared using val keyword can not be re-assigned once it has been assigned for the first time.

1
2
val firstname: String = "ligth bear" // Initialize a variable and assign a value to it
firstName = "new light bear" // Value can not be re-assigned

Basic Types

Data types determines the feature of the data and the size of memory needed to contain that data. Kotlin came with 5 built-in data types, number, character, boolean, array, and string.

Numbers

Numbers are grouped into 2:

  • Whole Numbers

    Type Size (in bit) Range
    Byte 8 -128 to 127
    Short 16 -32,768 to 32,767
    Int 32 -2,147,483,648 to 2,147,483,647
    Long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

    In Kotlin, if the data type of a variable is not specified during initialization, Kotlin will recognize the value as Int (if it is a number), even the data is within the range of Byte or Short. Long on the other hand will be recognized as the data type if the value exceed the range of Int. However, Long can be explicitly specified by using ‘L’ as the suffix of the value.

    1
    2
    3
    4
    var one = 1 // Int type even it is within the range of Byte or Short
    var ten: Byte = 10 // Specify the type as Byte
    var threeBillion = 3000000000 // Long type since it exceeds the range of Int
    var oneHundred = 100L // Explicitly specify Long data type

    Although the use of data type with a smaller size means the code will consume less memory, this memory saving does not worth the confusion caused by the code when it gets more complicated. Moreover, computer now a days provide a huge memory and programmers should focus on the performance instead.

  • Floating-Point Numbers

    Type Size (in bit) Significant Digits Range
    Float 32 16 - 18 1.4E-45 to 3.4028235E38
    Double 64 6 - 8 4.9E-324 to 1.7976931348623157E308

    The floating-point numbers or also known as decimal numbers are divided into Float and Double. The main difference is Float type has less precision when compared to Double type. It means that if number with Float type has significant digits more than the limit (6 - 7), it will be rounded.

    Similar to how Int is recognized default by Kotlin, Double will be recognized as the type default instead of Float if the data type is not specified during initialization. The Float type must be explicitly specified by using ‘f’ as the suffix of the value in order to have a Float typed variable.

    1
    2
    3
    4
    5
    var pi = 3.141592653589793 // Double type
    var piFloat = 3.141592653589793f // Float type

    println(pi) // Outputs: 3.141592653589793
    println(piFloat) // Outputs: 3.1415927

Underscore Helper

Underscores can be used in number values to improve readability:

1
2
3
var oneBillion: Int = 1_000_000_000 
var aVeryBigNumber: Long = 350_814_702_139_901_275
var aVeryLongDecimal: Double = 0.104_714_092_375

Conversions

Kotlin does not support implicit widening conversion for numbers (convert smaller type to bigger type). Unlike other programming language where Int type can be directly converted into Long when assigned to a Long typed variable.

1
2
var integerNumber: Int = 1_000_000
var longNumber: Long = integerNumber // Error

In the example above, in order for the value of ‘integerNumber’ can be assigned to ‘longNumber’, we need to explicitly convert it by calling toLong() function[^1] at the end of ‘integerNumber’.

1
2
var integerNumber: Int = 1_000_000
var longNumber: Long = integerNumber.toLong() // Explicitly converts type integer to type long

Every number type in Kotlin supports these conversions:

Function Convert a number to type
toByte() Byte
toShort() Short
toInt() Int (Integer)
toLong() Long
toFloat() Float
toDouble() Double
toChar() Char (Character)

NOTE: In the newer version of Kotlin, floating-point numbers are can no longer be directly converted to Byte and Short. They need to be converted to other types such as Int beforehand.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var doubleNumber: Double = 100_000.000_000_1

var byteNumber: Byte = doubleNumber.toInt().toByte() // Converts to Byte
var shortNumber: Short = doubleNumber.toInt().toShort() // Converts to Short
var integerNumber: Int = doubleNumber.toInt() // Converts to Int
var floatNumber: Float = doubleNumber.toFloat() // Converts to Float
var character: Char = doubleNumber.toChar() // Converts to Char
var string: String = doubleNumber.toString() // Converts to String
var aNewdoubleNumber: Double = doubleNumber.toDouble() // Redundant, no need to convert since it is already a Double

println(byteNumber) // Outputs: -96
println(shortNumber) // Outputs: -31072
println(floatNumber) // Outputs: 100000.0
println(integerNumber) // Outputs: 100000
println(character) // Outputs: 蚠
println(string) // Outputs: 100000.0000001
println(aNewdoubleNumber) // Outputs: 100000.0000001

Referring to the example above, both ‘byteNumber’ and ‘shortNumber’ outputs negative numbers when printed because the value ‘doubleNumber’ exceeds the limit of both types. When this happens, the number will keep repeating from its lower limit every time after it reaches its upper limit. For example, a type Int variable with value 128 is being converted to Byte. Because the value 128 exceeds 127 (the limit of a type Byte) by 1 number, the converted number will be starting from the lower limit which is -128. So, it can be said that the number after 127 is -128. This case is also applies when a type Long is converted to type Int in which that number exceeds the limit of an Int type.

When a decimal number is being converted into non-decimal typed, the decimal numbers (numbers behind the ‘.’) will be automatically omitted as shown in the example above when ‘doubleNumber’ is converted to ‘byteNumber’, ‘shortNumber’, ‘integerNumber’, and ‘longNumber’.

A Double type number which has significant digits exceeding the Float type will be rounded when converted into Float.

When a number is converted into Char, it will be converted into the matching Unicode characters. On the other hand, if a number is converted into String type, the number maintains its form, only that its type becomes a String.

Characters

Type Size (in bits) Range
Char 16 bits 0 to 65535

A Char type data consists one of either alphabets (a-z and A-Z), numbers (0-9), whitespaces, or other special characters, which is surrounded by single quotes.

1
var character: Char = 'A'

Numbers in Char type are character different from numbers in Int type.

1
2
var aRealNumber: Int = 1
var characterNumber: Char = '1' // A character type number, different value with the value of 'aRealNumber' variable

Special characters such as single quotation can not be used since it is used as a notation to imply that the data is a Char. To use it, the special character is escaped by using a backslash.

1
2
var singleQuotation: Char = ''' // Error'
var escapedSincleQuotation: Char = '\'' // Escaped using a backslash

These are several escape characters supported in Kotlin:

Escape Character Explanation
\t A tab
\b A backspace
\n A newline
\r A carriage return
\‘ A single quotation
\“ A double quotation
\ A backslash
$ A dollar

To encode other character, use the Unicode sequence syntax:

1
2
3
var otherCharacter: Char = '\u00A9'

println(otherCharacter) // Outputs: ©

Explicit conversion in Char works the same with number’s explicit conversion. However, the result when a Char value is converted to Int or other number types will be the Unicode number.

1
2
3
4
var character: Char = 'A'
var number: Int = character.toInt()

println(number) // Outputs: 65

The number of characters available is 65536 from range 0 to 65535.

Booleans

Type Size (in bits) Value
Boolean 1 true or false

Boolean type is the smallest in size among the types in Kotlin, it consists of only 2 values, a true and a false, or represented as 1 and 0 respectively.

1
2
var aTrue: Boolean = true
var aFalse: Boolean = false

A Boolean can only be explicitly converted to String type by calling a toString() function[^1] from the variable and becomes a string type.

1
2
3
4
var aBoolean: Boolean = true
var convertedBoolean: String = aBoolean.toString()

println(convertedBoolean) // Outputs a string literal "true"

Arrays

Array is a collection of values held in a container. It is initialized by calling ‘arrayOf()’ function[^1], the values will be inserted between the parentheses of the function.

1
var array = arrayOf(1, 2, 3, 4, 5) // Initialize an array which contains numbers

Since an array holds values, it has size, the number of values inside the container. This size is fixed, once it is initialized, no data can be added anymore. The values in the array can be accessed by calling the variable name, followed by an open squared bracket, index number, and close squared bracket. The index is the position of the value, it starts with 0 and ends with ‘size of array - 1’.

1
2
3
4
5
var array = arrayOf(1, 2, 3, 4, 5) // Initialize an array containing 5 numbers (size is 5)

println(array[0]) // Calling value at index 0, Outputs: 1
println(array[4]) // Calling value at index 4 (last value), Outputs: 5
println(array[5]) // Error, no value at index 5 since the size of the array is 5

Values inside Array are mutable, which means they can be changed. It is done by calling the variable name like how it is done in accessing value, instead, we use the assignment operator and assign a value to it.

1
2
3
4
5
6
7
var array = arrayOf(1, 2, 3, 4, 5)

println(array[0]) // Outputs: 1

array[0] = 100 // Change the value at index 0

println(array[0]) // Outputs: 100

This topic will be further discussed in Collection chapter.

Strings

Value of String type is a collection of characters. Its concept is similar to an Array, however it is not created using a function[^1] but the characters are put in between a pair of double quotation.

1
2
3
var string: String = "Light Bear"

println(string) // Outputs: Light Bear

A character in a String can be accessed like how the data can be accessed in Array. However characters in a String are immutable, so they can not be changed once initialized.

1
2
3
4
5
var string: String = "Light Bear"

println(string[0]) // Outputs: L

string[0] = "R" // Error, characters are immutable

A string can contain template expression, a piece of code whose result will be concatenated into the string. A dollar sign is needed as a prefix to start the template. A pair of curly braces can be used to create more complex template.

1
2
3
4
5
6
7
var bearCount: Int = 15
println("Number of bear is $bearCount") // Outputs: Number of bear is 15

var youngBearCount: Int = 5
var oldBearCount:Int = 10
println("Total number of bear is ${youngBearCount + oldBearCount}")
// Outputs: Total number of bear is 15

Creating a new line in String can not be done by using enter key as shown in the following example:

1
2
3
4
5
// Error
var string: String = "
First Line
Second Line
"

It can however be done in 2 ways:

  • Using escape string

    Escape string is a string that may contains escape characters in them. The single quotation does no needed to mark the escape character, it can be simply inserted between or without any characters sandwiched between double quotation.

    1
    2
    3
    4
    5
    6
    7
    var escapeString: String = "First Line\nSecond Line"

    println(escapeString)

    // Outputs:
    // First Line
    // Second Line

    Other escape characters also can be used in a string. One of the common use case is output the double quotation since the symbol is already used in marking a String. The dollar sign ($) is the other example, it is already used to mark a template expression, we need to escape it in order to output the actual dollar sign.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var string: String = ""Light Bear"" // Error


    var escapeString: String = "\"Light Bear\""
    println(escapeString) // Outputs: "Light Bear"


    val money: Int = 100
    var escapeString: String = "Money: \$${money}"
    println(escapeString) // Outputs: "Money: $100"
  • Using raw string

    A raw string is declared using triple quote (“””). Now, every time the enter key is hit, a new line will be created. This allows us to write a long paragraph without the need to write in a long line. A raw string can not contain any escape character except for string template (a dollar sign with or without curly braces) and so it can contain characters such as double quotation and backslash without the need of escaping them.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    var rawString: String = """ Line 1
    Line 2\
    "Line 3"
    Line 4"""

    println(rawString)

    // Outputs:
    // Line 1
    // Line 2\
    // "Line 3"
    // Line 4

    Notice the indentation in the output in the example above, this can be solved by calling ‘trimMargin()’ function[^1] at the end of the raw string. The straight line character (|) is chosen as default to the indentation, it can be changed by inserting a symbol of type String in between the parentheses.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    var rawString = """Line 1
    |Line 2\
    |"Line 3"
    |Line 4""".trimMargin()

    println(rawString)


    var rawString2 = """Line 1
    >Line 2\
    >"Line 3"
    >Line4""".trimMargin(">")

    println(rawString2)

    // Both 'rawString' and 'rawString2' outputs the same result
    // Outputs:
    // Line 1
    // Line 2
    // "Line 3"
    // Line 4

    One simple trick to use the escape character in raw string is by using the string template, even though it makes the code longer.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // Using Unicode sequence syntax in raw string by using string template
    var rawString = """=====
    Light ${"\n"} Bear ${"\u263A"}
    ====="""

    println(rawString)

    // Outputs:
    //=====
    // Light
    // Bear ☺
    //=====

Operators

Operators are special characters that can carry out operations on operands. For example:

$2 + 3$

The example above is called as an operation called as addition, both numbers ‘2’ and ‘3’ are operands, the ‘+’ symbol is the operator. The addition operation will results in ‘5’ from the sum of ‘2’ and ‘3’. One of the operator discussed on topic ‘Variable’ is the assignment operator, used to assign a value/operand to the variable. There are several commonly used basic operators which will be discussed, mainly, arithmetic operators, assignment operator, unary operators, comparison and equity operators, and logical operators.

Arithmetic Operator

Several basic arithmetic operator in Kotlin:

Operator Function
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo (remainder)
1
2
3
4
5
6
7
8
9
10
11
var addition = 1 + 2
var subtraction = 1 - 2
var multiplication = 1 * 2
var division = 2 / 1
var modulo = 3 % 2

println(adition) // Outputs: 3
println(subtraction) // Outputs: -1
println(multiplication) // Outputs: 2
println(division) // Outputs: 2
println(modulo) // Outputs: 1

All of the operator works similar to how we do math and to other programming languages. However there is one thing to note about the division in Kotlin, it always resulted in Int type.

1
2
var equation = 3 / 2 // Expected: 1.5
println(equation) // Outputs: 1

To solve this problem, at least one of the numbers is supposed to be a decimal either by using conversion or explicit specification.

1
2
3
4
5
6
7
8
9
10
var equation = 3 / 2.0 // Explicit specification
println(equation) // Outputs: 1.5

var equation2 = 3.0 / 2 // Explicit specification
println(equation2) // Outputs: 1.5

var numA = 3
var equation3 = numA.toDouble() / 2 // Conversion
println(equation3) // Outputs: 1.5

Level of operators’ precedence exists in Kotlin. An operator with higher level precedence will be calculated first before the lower precedence. The following list starts from the highest and ends at the lowest:

  • ‘()’ - parentheses
  • ‘%’
  • ‘*’ or ‘/‘
  • ‘+’ or ‘-‘

Unlike some programming languages such as c++ where Boolean types can be calculated, for instance:

  • $true + false$ will result in 1
  • $true + 2$ will result in 3

This is because a true will be converted to 1 and false will be converted to 0 in case of calculation. However, Kotlin does not support this feature.

Apart from Boolean, Char type value also can not be calculated because they are single character. Nevertheless, String type value can be calculated with only addition (+), concatenation is a more precise term.

1
2
3
4
var string1: String = "light"
var string2: String = "bear"
var concatenatedString: String = string1 + " " + string2
println(concatenatedString) // Outputs: "light bear"

Other types (Numbers, Char, and Boolean) can be concatenated to a string, this is because most of the types can be converted into String by calling toString(), this is done implicitly in the case of concatenation. However, the string must be the first or at the left side of the ‘+’ operator.

1
2
3
4
5
6
7
8
9
10
11
12
var string: String = "light"
var number: Double = 2.0
var boolean: Boolean = true
var character: Char = '^'

println(string + number) // Outputs: light2.0
println(string + boolean) // Outputs: lighttrue
println(string + character) // Outputs: light^
println(string + number + boolean + character) // Outputs: light2.0true^

println(number + string) // Error
println(character + number + string + boolean) // Error

NOTE: It is recommended to use string template than concatenation with plus (+) operator to avoid the arrangement error as shown in the previous example.

1
2
3
4
5
6
var string1: String = "light"
var string2: String = "bear"
var character: Char = 'V'
var number: Boolean = 2.0

println("$string1 $string2 $character$number") // Outputs: light bear V2.0

Assignment Operator

Operator Function
= Assignment

The assignment operator is used to assign values from the right side to the variable on the left side.

1
var number: Int = 1 // Assign value '1' to 'number' variable

The assignment operator can also be combined with arithmetic operators:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var a = 5
var b = 3

a += b // Equals to 'a = a + b'
a -= b // Equals to 'a = a - b'
a *= b // Equals to 'a = a * b'
a /= b // Equals to 'a = a / b'
a %= b // Equals to 'a = a % b'

// A more complex example
a += 1 + (b / 2) * 3 // Equals to 'a = a + 1 + (b / 2) * 3 '

// String concatenation
var c = ""
c += a + b // Equals to 'c = c + a + b'
println(c) // Outputs: 53

Unary Operator

The unary operator is an operator that operates with only one operand. Both arithmetic and assignment operators are binary operator because they need at least 2 operands to operate.

1
2
3
2 + 3 // Operator: '+' // Operands: '2' and '3'
var a = 2 // Operator: '=' // Operands: 'a' and '2'
var b = 2 + 3 // Operator: '=' and '+' // Operands: 'b', '2', and '3'

Here are some basic unary operators in Kotlin:

Operator Function Use Case
+ Positive +a
- Negative -a
! Negation !a
++ Increment ++a and a++
Decrement –a and a–

The usage of minus symbol as a unary operator is usually used in declaring a negative number/value. The positive symbol however is rarely used or at least explicitly used, this is because the positive number is the default of numbers.

1
2
3
4
var negativeNumber: Int = -2 // Assignment of a negative number
var result: Int = 5 - -2 // Equals to '5 - (-2)' or '5 + 2'
var result: Int = 5 - +2 // Rarely used because '2' itself is a postive number
var result: Int = 5 +- 2 // Error, watch out the spaces

The exclamation operator is used in negation and this mostly deals with Booleans.

1
2
var isTrue: Boolean = !true // Equals to false
println(isTrue) // Outputs: false

The increment (++) and decrement (–) operators are used to increase a value by 1 and decrease a value by 1 respectively.

1
2
3
4
5
6
7
var increment: Int = 0
++increment // Increment the value in 'increment' by 1 // Equals to increment += 1
println(increment) // Outputs: 1

var decrement: Int = 3
decrement = 5 + --decrement // Decrement the value in 'decrement' by 1 // Equals to decrement -= 1
println(decrement) // Outputs: 7

The increment or decrement operator preceding the operand (pre-increment or pre-decrement) is different from the one succeeding the operand (post-increment or post decrement):

1
2
3
4
5
6
7
8
9
// First Example
var preIncrement: Int = 0
var result: Int = 1 + ++preIncrement // preIncrement value: 1 // Equals to '1 + 1'
println(result) // preIncrement value: 1 // Outputs: 2

// Second Example
var preIncrement2: Int = 0
var result2: Int = 1 + preIncrement++ // preIncrement value: 0 // Equals to '1 + 0'
println(result2) // preIncrement value: 1 // Outputs: 1

The unary operator used in the first example is a pre-increment, the second example shows a post-increment. The way it works in the first example is, the ‘preIncrement’ will be incremented first before added with ‘1’. However in the second example, the ‘preIncrement2’ will not do the increment, instead, the initial ‘0’ value will be used to do the addition with ‘1’. Once the expression is done, then the ‘preIncrement2’ will be incremented.

The unary operators have higher precedence than any of arithmetic operators.

Comparisons and Equality Operators

The following table shows different kind of comparison operators:

Operator Function
> Greater than
>= Greater than or equal to
< Smaller than
<= Smaller than or equal to
== Equal to
!= Not equal to

The comparison operators is used to compare integers, strings, characters, and booleans. The type however should be of the same, an integer should be compared to another integer, a string with another string, and so on. The result of the comparison is a boolean.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Example 1
var zero: Int = 0
var one: Int = 1
var compareResult: Boolean = zero > one
println(compareResult) // Outputs: false

// Example 2
var integerZero: Int = 0
var charZero: Char = '0'
var compareResult2: Boolean = integerZero == charZero // Error

// Example 3
var string1: String = "light bear"
var string2: String = "Light bear"
var compareResult3: Boolean = string1 > string2
println(compareResult) // Outputs: True

The way Char type is being compared is based on their value (the index/number in Unicode table). When comparing strings, each of the characters will be compared accordingly, in ‘Example 3’:

The comparison will start from left to right. Because ‘l’ (value: 108) is bigger than ‘L’ (value: 76) during the first comparison, it is concluded ‘Light bear’ has larger value than ‘light bear’. This will also applies even if ‘Light bear’ has more characters.

1
println("light bear" > "Light bearssssss") // Outputs: true

Unless both operands have identical characters and one of the operand slightly longer or has an extra character, then the longer one will be considered as larger value.

1
2
// Compares a 'light bear' without 's' with the one with 's'
println("light bear" > "light bears") // Outputs: true

[^1]: Function is concept which will be discussed in the later chapter. For now, bear that a function is a keyword that literally has a function or is functional. The keyword is followed by a pair of open and close parentheses without any spaces between the keyword and the open parenthesis. e.g. println() has a function to print/output anything inserted between the parentheses, to the console.

Author

Ravel Tanjaya

Posted on

2020-12-04

Updated on

2020-12-04

Licensed under