Kotlin Data Types

Posted: 12 Jul 2021. Last modified on 27-May-22.

This article will take about 1 minute to read.


Unit:

Nothing: - Indicates that this function will never return (always throws an exception) - When used as a return type, it doesn’t affect inferred types - Is the subtype of all other types.

Collections: The collection interface supports only read-only methods while the MutableCollection interface supports read/write methods.

There are other similar collection literals, such as ||| |–|–| |listOf()|mutableListOf()| |setOf()|mutableSetOf()| |mapOf()|mutableMapOf()|

However, read-only does not mean that they are fully immutable. The underlying object can still be changed.

fun funWithLists(){
    val m = mutableListOf(1,2,3)
    val list: List<Int> = m

    println(list) // [1, 2, 3]

    m.add(4)

    println(list) // [1, 2, 3, 4]

    list.add(5) // ERROR!

}

Sequences

However, if you try to evaluate an infinite list all at once, you will get an OutOfMemoryError, so watch out!

Other built in methods:

Resources: Kotlin Types: Exposed The Road to Kotlintown: Part 1 The Road to Kotlintown: Part 2 Kotlin in Action by Dmitry Jemerov and Svetlana Isakova

Koans (let’s start here): https://play.kotlinlang.org/byExample/01_introduction/04_Null%20Safety