What are the most Frequently Asked Questions about Kotlin?

This is an edited compilation of 48 questions and their respective answer about the Kotlin Language.

Question: How to check if a lateinit variable has been initialized?

Answer: Using .isInitialized property you can the check initialization state of a lateinit variable, for example:

if(::file.isInitialized){
                    //File is initialized
                }else{
                    //File is not initialized
                }

Source

Question: What is the equivalent of the “a ? b : c” expression in Kotlin?

Answer: In Kotlin, if statements are expressions. So the expression “a ? b : c” is equivalent to:

if (a) b else c

The distinction between expression and statement is important here. In Java, C# or JavaScript, if forms a statement, meaning that it does not resolve to a value. More concretely, you can not assign it to a variable.

The following is valid in Kotlin, but it is invalid in Java, C#, or JavaScript.

var v = if (a) b else c

Source

Question: What is the difference between var and val in Kotlin?

Answer: In Kotlin, you can use val and var to declare a variable. var is like general variable and it is known as a mutable variable in Kotlin and can be assigned multiple times. val is like Final variable and it is known as immutable in Kotlin and can be initialized only single time.

Source

Question: How to initialize MutableList to empty MutableList in Kotlin?

Answer: In Kotlin, you can simply write, for example:

val mutableList = mutableListOf<Kolory>()

This is the most idiomatic way. Alternative ways are, for example:

val mutableList : MutableList<Kolory> = arrayListOf()

or

val mutableList : MutableList<Kolory> = ArrayList()

Source

Question: What is the difference of property initialization using “by lazy” vs. “lateinit” in Kotlin?

Answer: Unlike lazy initialization, lateinit allows the compiler to recognize that the value of the non-null property is not stored in the constructor stage to compile normally. by lazy may be very useful when implementing read-only properties that perform lazy initialization in Kotlin, by lazy { ... } performs its initializer where the defined property is first used, not its declaration.

Source

Question: What is the difference between const and val in Kotlin?

Answer: const are compile time constants, this means that their value has to be assigned during compile time, unlike val, where it can be done at runtime. This implies that const can never be assigned to a function or any class constructor, but only to a String or primitive.

Source

Question: What is the difference between List and Array types in Kotlin?

Answer: The major difference from usage is that Arrays have a fixed size while (Mutable)List can adjust their size dynamically. Moreover Array is mutable whereas List is not.

Furthermore kotlin.collections.List is an interface implemented among others by java.util.ArrayList. It's also extended by kotlin.collections.MutableList to be used when a collection that allows for item modification is needed.

On the jvm level Array is represented by arrays. List on the other hand is represented by java.util.List since there are no immutable collections equivalents available in Java.

Source

Question: How to initialize an array with values in Kotlin?

Answer: There are several ways to initialize an array with values. For example:

var arr = IntArray(size) // construct with only size

Then simply initial value from users or from another collection or wherever you want.

var arr = IntArray(size){0}  // construct with size and fill array with 0
                var arr = IntArray(size){it} // construct with size and fill with its index

You also can create an array with built-in function like

var arr = intArrayOf(1, 2, 3, 4, 5) // create an array with 5 values

Source

Question: How to convert String to Long or Int in Kotlin?

Answer: Extension methods are available for String to parse them into other primitive types. For example:

"10".toLong()
                "10".toInt()

Source

Question: How to pass a function as a parameter to another in Kotlin?

Answer: Since Kotlin 1.1, you can now use functions that are class members, Bound Callable References, by prefixing the function reference operator with the instance.

Source

Question: What is the single exclamation mark in Kotlin?

Answer: This exclamation mark is called platform types and it means that Kotlin does not know whether that value can or cannot be null and it is up to you to decide if it is nullable or not.

Source

Question: How to have any formatting in the Kotlin templates?

Answer: There is no built-in support for formatting in string templates, as a workaround, you can use, for example:

"pi = ${pi.format(2)}"

Source

the .format(n) function you would need to define yourself as:

fun Double.format(digits: Int) = "%.${digits}f".format(this)

Question: What how to define a var that has a public getter and private setter in Kotlin?

Answer: By default, all properties and functions are public in Kotlin. Hence the setter has to be explicitly declared private while the getter is public by default. For example:

var name : String = "Peter"
                    private set

Source

Question: What is the double-bang !! operator in Kotlin?

Answer: The double bang is the unsafe nullable type (T?) conversion to a non-nullable type (T), !! will throw NullPointerException if the value is null.

Source

Question: How to convert List to Map in Kotlin?

Answer: With Kotlin 1.3, List has a function called associate. associate has the following declaration:

fun <T, K, V> Iterable<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V>

returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.

Source

Question: What is the difference between ArrayList<String>() and mutableListOf<String>() in Kotlin?

Answer: As you can see in the Source code:

public inline fun <T> mutableListOf(): MutableList<T> = ArrayList()

there is no difference, it is just a convenience method.

Source

Question: What does the Elvis operator ?: do in Kotlin?

Answer: The Elvis operator is represented by a question mark followed by a colon: ?: and it can be used with this syntax:

first operand ?: second operand

It enables you to write concise code, and works as such:

If the first operand is not null, then it will be returned. If it is null, then the second operand will be returned. This can be used to guarantee that expression will not return a null value, as you'll provide a non-nullable value if the provided value is null.

Source

Question: How do define a static extension method in Kotlin?

Answer: Kotlin generates static methods for package-level functions. Kotlin can also generate static methods for functions defined in named objects or companion objects if you annotate those functions as @JvmStatic, for example:

class C {
                  companion object {
                    @JvmStatic fun foo() {}
                    fun bar() {}
                  }
                }

Source

Question: What is the difference between an IntArray and an Array<Int> in Kotlin?

Answer: Array<Int> is an Integer[] under the hood, while IntArray is an int[]. This means that when you put an Int in an Array<Int>, it will always be boxed (specifically, with an Integer.valueOf() call). In the case of IntArray, no boxing will occur, because it translates to a Java primitive array.

Source

Question: How to extend data classes in Kotlin?

Answer: Data classes do not play too well with inheritance. For example, it is known that there is no way to implement equals() correctly in a hierarchy of non-abstract classes.

Source

Question: How to catch many exceptions at the same time in Kotlin?

Answer: Although multi-catch in Kotlin is not yet supported, there some alternatives. For example:

fun (() -> Unit).catch(vararg exceptions: KClass<out Throwable>, catchBlock: (Throwable) -> Unit) {
                    try { 
                        this() 
                    } catch (e: Throwable) {
                        if (e::class in exceptions) catchBlock(e) else throw e
                    }
                }

Source

Question: What does 'by' keyword do in Kotlin?

Answer: In simple words, you can understand by keyword as provided by. From the perspective of property consumer, val is something that has getter (get) and var is something that has getter and setter (get, set). For each var property, there is a default provider of get and set methods that we do not need to specify explicitly.

Source

Question: What is the difference between launch/join and async/await in Kotlin coroutines?

Answer: launch is used to fire and forget coroutine. It is like starting a new thread. If the code inside the launch terminates with an exception, then it is treated like an uncaught exception in a thread. join is used to wait for the completion of the launched coroutine and it does not propagate its exception. However, a crashed child coroutine cancels its parent with the corresponding exception, too.

async is used to start a coroutine that computes some results. The result is represented by an instance of Deferred and you must use await on it. An uncaught exception inside the async code is stored inside the resulting Deferred and is not delivered anywhere else, it will get silently dropped unless processed. You must not forget about the coroutine you have started with async.

Source

Question: What is the difference between with and apply in Kotlin?

Answer: There are two differences. First, apply accepts an instance as the receiver while with requires an instance to be passed as an argument. In both cases, the instance will become this within a block. Second, apply returns the receiver and with returns a result of the last expression within its block.

Source

Question: How to generate a random number in Kotlin?

Answer: As of Kotlin 1.3, comes with its multi-platform random generator. The extension described below is now part of the Kotlin standard library, simply use it like this:

val rnds = (0..10).random()

Source

Question: How to read the entire contents of an InputStream into a String, in Kotlin?

Answer: Kotlin has a specific extensions just for this purpose, for example:

val inputAsString = input.bufferedReader().use { it.readText() }

You could decide between bufferedReader() or just reader(). The call to the function Closeable.use() will automatically close the input at the end of the lambda's execution.

Source

Question: Is Kotlin “pass-by-value” or “pass-by-reference”?

Answer: Kotlin is always pass-by-value.

Source

Question: Why is a generic typed property nullable in Kotlin?

Answer: The default upper bound, if none specified, is Any?. In other words, when you use T, Kotlin assumes that this might be any type, be it primitive, object, or a nullable reference.

Source

Question: How to swap to elements in Kotlin?

Answer: You can use the existing also function. For example:

var a = 1
                var b = 2
                a = b.also { b = a }

Source

Question: How to effectively use Enums with reverse lookup in Kotlin?

Answer: You can use find which returns the first element matching the given predicate, or null if no such element was found, for example:

companion object {
                   fun valueOf(value: Int): Type? = Type.values().find { it.value == value }
                }

Source

Question: How to remove duplicate strings from an array in Kotlin?

Answer: You can use the distinct extension function, for example:

val a = arrayOf("a", "a", "b", "c", "c")
                val b = a.distinct()

Source

Question: Are there constructor references in Kotlin?

Answer: You can get a function instance for a constructor by simply using ::ClassName, as if it were a factory function.

Source

Question: What does the asterisk mean before variable name in Kotlin?

Answer: The * operator is known as the Spread Operator in Kotlin. When you call a vararg function, you can pass arguments one-by-one, for example, asList(1, 2, 3), or, if you already have an array and want to pass its contents to the function, you use the spread operator (prefix the array with *).

Source

Question: Is it possible to omit unused interface methods in Kotlin?

Answer: You may only implement one interface method, all you have to do is to provide a default implementation for the other methods in the interface declaration

Source

Question: What is the difference between fold and reduce in Kotlin?

Answer: fold takes an initial value, and the first invocation of the lambda you pass to it will receive that initial value and the first element of the collection as parameters. However, reduce does not take an initial value, but instead starts with the first element of the collection as the accumulator.

Source

Question: What is the difference between apply and also in Kotlin?

Answer: The also function takes a lambda in which you refer to the object you called the function on (receiver T) with either it (implicit name) or a custom name. With apply, on the other hand, a function literal with receiver is used so inside the passed in lambda you can access the receiver’s members directly.

Source

Question: How to create an empty array in Kotlin?

Answer: You can use the Kotlin standard library function. For example:

public fun <T> arrayOf(vararg t: T): Array<T>

Source

Question: How to check if lazy val has been initialized in Kotlin?

Answer: Since Kotlin 1.1, you can access a property delegate directly using .getDelegate(). You can write an extension property for a property reference that checks that it has a Lazy delegate that has already been initialized.

Source

Question: How to turn a mutable collection into an immutable one in Kotlin?

Answer: In the Kotlin stdlib there are no implementations of List<T> (Map<K,V>) that would not also implement MutableList<T> (MutableMap<K,V>). However, due to Kotlin's delegation feature, the implementations become simple, for example:

class ImmutableList<T>(private val inner:List<T>) : List<T> by inner
                class ImmutableMap<K, V>(private val inner: Map<K, V>) : Map<K, V> by inner

Source

Question: What does a Kotlin function signature with T.() mean? Answer: T.() -> Unit is an extension function type with receiver. Besides ordinary functions, Kotlin supports extension functions. Such function differs from an ordinary one in that it has a receiver type specification.

Source

Question: How to use List iteration without extra object allocations?

Answer: In Kotlin, there is only one allocation-less way to define a for loop. For example:

for (i in 0..count - 1)

All other forms lead to either a Range allocation or an Iterator allocation. Unfortunately, you cannot even define an effective reverse for a loop.

Source

Question: What is the difference between constant in companion object and top-level in Kotlin?

Answer: Defining the field in a companion object limits the scope it is available in without importing to only that class, which can help to keep the data from being used in unexpected places. While defining in the file makes the field available to any code in the same package as the field.

Source

Question: How to add an item to an ArrayList in Kotlin?

Answer: If you have a mutable collection, you can use, for example:

val list = mutableListOf(1, 2, 3)
                list += 4

You should note that you use val for the mutable list to emphasize that the object is always the same, but its content changes.

However, if you have an immutablr collection, you should use, for example:

var list = listOf(1, 2, 3)
                list += 4

In the case of the immutable list, you have to make it a var. A new object is created by the += operator with additional value.

Source

Question: How to check instanceof class in Kotlin?

Answer: You can check whether an object conforms to a given type at runtime by using the is operator or its negated form !is. For example:

if (obj is String) {
                    print(obj.length)
                }
                
                if (obj !is String) {
                    print("Not a String")
                }

Source

Question: How to correctly concatenate a String in Kotlin?

Answer: In Kotlin, you can concatenate using string interpolation or templates, for example:

val a = "Hello"
                val b = "World"
                val c = "$a $b"

You can also concatenate using the + or plus() operator, for example:

val a = "Hello"
                val b = "World"
                val c = a + b   // same as calling the function a.plus(b)

All resulting strings will be “HelloWorld”.

Source

Question: How to use break and continue in forEach in Kotlin?

Answer: You can write break and continue in `forEach using annotations. For example:

fun foo() {
                    listOf(1, 2, 3, 4, 5).forEach lit@{
                        if (it == 3) return@lit
                    }
                }

Source

Question: How to declare several properties on one line in Kotlin?

Answer: In Kotlin, there is no way to do that. Declaring multiple properties on the same line are frowned upon, in many Java style guides, so there is no support for that in Kotlin.

Source