logo

Kotlin

Last Updated: 2024-01-22

What are data classes?

Data classes are used to hold data. You do not need to explicitly write constructors, getters, equals(), hashCode(), copy(), toString(), etc; the compiler will generate them.

For example:

data class Foo(val field1: String, val field2: Int)

How to avoid NullPointerException in Kotlin?

  • by default variable are non-nullable; to make it nullbale, add ?, e.g. var a: String?.
  • use Safe Call operator (?.): foo?.bar(), if foo is null, return null instead of throwing NPE.
  • use Elvis operator (?:): foo ?: bar, if foo is not null, return foo, otherwise return bar.

If you want to throw an NPE:

  • use Not Null Assertion Operator ( !! ): str!!.length, if str is null, throw a NPE.
  • An explicit call to throw NullPointerException()

What's the difference between a primary constructor and secondary constructors?

  • A Kotlin class can have ONE primary constructor and ONE or MORE secondary constructors.
  • The primary constructor is a part of the class header:
    • class Person constructor(firstName: String) {}, or
    • class Person(firstName: String) {} (If the primary constructor does not have any annotations or visibility modifiers, the constructor keyword can be omitted).
  • If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s).

What's the difference between lateinit and lazy?

  • lateinit var delays the initialization to a later time; it can be initialized anywhere in the program; could have multiple initializations; not thread-safe; only var; primitive type not allowed. Use it if properties are mutable.
  • lazy initializes the object only when it is used; it can only be initialized by initializer lambda; only a single initialization; thread-safe; can use val; allow on primitive type properties.

What is a suspend function?

Suspend function: a function that may be started, halted, then resumed. delay() function is an example of suspend function.

What is sealed class?

Sealing allows classes and interfaces to define their permitted subtypes. A class or an interface can now define which classes can implement or extend it. The main motivation behind sealed classes is to have the possibility for a superclass to be widely accessible but not widely extensible.

Where is the main class?

Suppose HelloWorld.kt has the following code, the main() is not in a class, what is the "main class"?

package com.example

fun main() {
    println("Hello, World!")
}

It turns out that the compiler wraps it in a class, and the main class is com.example.HelloWorldKt.

Kotlin vs Java

https://kotlinlang.org/docs/comparison-to-java.html

Java has primitive types, Kotlin does not