Kotlin Common Questions

(Last Updated On: August 17, 2018)

1. Where should we keep constants in Kotlin?

  • if you need constants to be accessed globally use const as top-level properties (not inside a class).

In order to do this create a Kotlin file named Constants.kt. The file would look like this:

This way you will be able to access the constants from anywhere within the app just by typing the constant name (in Kotlin code). In Java code you will need to write ConstantsKt.MY_APP_ID.

  • if you have constants that are specific to a scope, like Employee for example, create a companion object

And this is how you use the constants.

2. What do ?, ?., ?: and !! mean?

3. How to make casts in Kotlin?

4. How to use Parcelable in Kotlin?

5. How to create a Singleton in Kotlin?

6. How to create a List in Kotlin?

List

List

  • Create a List in Kotlin

Important!

In Kotlin, lists are immutable by default (you can’t add or remove elements after the list is created). If you need to make a list mutable, you can do this by using mutableListOf

OR

by creating an ArrayList.

BUT it should be just a temporary list. It is not recommended to keep mutable lists for too long.

  • Mixed types

When you create a list in Kotlin, you can add mixed types to the same list:

  • listOfNotNull() Function

The output of the above code will be this:

Notice that null values are ignored.

  • Empty lists

There are 2 ways to create empty lists. They do the same thing, so it’s up to you which way you prefer.

OR

emptyList<String>() returns an Immutable empty list.

7. How to create a SET in Kotlin?

  • Create a Set in Kotlin

  • Create a HashSet

  • Create a SortedSet (TreeSet in Java)

  • Create a LinkedSet (LinkedHashSet in Java)

 

8. How to create a Map in Kotlin?

  • Create a Map

  •  How to iterate a Map?

HashMap, LinkedMap (LinkedHashMap in Java) and SortedMap are all mutable.

9. What collection methods are useful?

any()

Returns true if collection has at least one element.

any(predicate: (T) -> Boolean

Returns true if at least one element matches the given predicate.

 

asReversed()

Returns a reversed read-only view of the original List.

Output