Kotlin MCQs

Kotlin MCQs

These Kotlin multiple-choice questions and their answers will help you strengthen your grip on the subject of Kotlin. You can prepare for an upcoming exam or job interview with these 50+ Kotlin MCQs.
So scroll down and start answering.

1: Kotlin interfaces and abstract classes are very similar. What is one thing abstract class can do that interfaces cannot?

A.   Only abstract classes are inheritable by subclasses

B.   Only abstract classes can inherit from multiple superclasses

C.   Only abstract classes can have abstract methods

D.   Only abstract classes can store state

2: Inside an extension function, what is the name of the variable that corresponds to the receiver object

A.   The variable is named it

B.   The variable is named this

C.   The variable is named receiver

D.   The variable is named default

3: What is the entry point for a Kotlin application?

A.   Fun static main(){}

B.   Fun main(){}

C.   Fun Main(){}

D.   Public static void main(){}

4: You are writing a console app in Kotlin that processes test entered by the user. If the user enters an empty string, the program exits. Which kind of loop would work best for this app? Keep in mind that the loop is entered at least once

A.   A do..while loop

B.   A for loop

C.   A while loop

D.   A forEach loop

5: You have started a long-running coroutine whose job you have assigned to a variable named task. If the need arose, how could you abort the coroutine? val task = launch { // long running job}

A.   Task.join()

B.   Task.abort()

C.   Job.stop()

D.   Task.cancel()

6: You are attempting to assign an integer variable to a long variable, but Kotlin compiler flags it as an error. Why?

A.   You must wrap all implicit conversion in a try/catch block

B.   You can only assign Long to an Int, not the other way around

C.   There is no implicit conversion from Int to Long

D.   All integers in Kotlin are of type Long

7: The function typeChecker receiver a parameter obj of type Any. Based upon the type of obj, it prints different messages for Int, String, Double, and Float types; if not any of the mentioned types, it prints "unknown type". What operator allows you to determine the type of an object?

A.   Instanceof

B.   Is

C.   Typeof

D.   As

8: This code does not print any output to the console. What is wrong? firstName?.let { println("Greeting $firstname!")}

A.   FirstName?.let { println(

B.   A null pointer exception is thrown

C.   FirstName is equal to null

D.   FirstName is equal to an empty string

E.   FirstName is equal to Boolean false

9: Which line of code shows how to display a nullable string's length and shows 0 instead of null?

A.   Println(b!!.length ?: 0)

B.   Println(b?.length ?: 0)

C.   Println(b?.length ?? 0)

D.   Println(b == null? 0: b.length)

10: In the file main.kt, you are filtering a list of integers and want to use an already existing function, removeBadValues. What is the proper way to invoke the function from filter in the line below? Val list2 = (80..100).toList().filter(_____)

A.   ::removeBadValues

B.   GlobalScope.removeBadValues()

C.   Mainkt.removeBadValues

D.   RemoveBadValues

11: Which code snippet correctly shows a for loop using a range to display "1 2 3 4 5 6"?

A.   for(z in 1..7) println("$z ")

B.   for(z in 1..6) print("$z ")

C.   for(z in 1 to 6) print("$z ")

D.   for(z in 1..7) print("$z ")

12: You are upgrading a Java class to Kotlin. What should you use to replace the Java class's static fields?

A.   An anonymous object

B.   A static property

C.   A companion object

D.   A backing field

13: Your code need to try casting an object. If the cast is not possible, you do not want an exception generated, instead you want null to be assigned. Which operator can safely cast a value?

A.   As?

B.   ??

C.   Is

D.   As

14: Kotlin will not compile this code snippet. What is wrong? class Employee class Manager : Employee()

A.   In order to inherit from a class, it must be marked open

B.   In order to inherit from a class, it must be marked public

C.   In order to inherit from a class, it must be marked sealed

D.   In order to inherit from a class, it must be marked override

15: Which function changes the value of the element at the current iterator location?

A.   Change()

B.   Modify()

C.   Set()

D.   Assign()

16: What three methods does this class have? Class Person

A.   Equals(), hashCode(), and toString()

B.   Equals(), toHash(), and super()

C.   Print(), println(), and toString()

D.   Clone(), equals(), and super()

17: Which is the proper way to declare a singleton named DatabaseManager?

A.   Object DatabaseManager {}

B.   Singleton DatabaseManager {}

C.   Static class DatabaseManager {}

D.   Data class DatabaseManager {}

18: In order to subclass the Person class, what is one thing you must do? abstract class Person(val name: String) { abstract fun displayJob(description: String)}

A.   The subclass must be marked sealed

B.   You must override the displayJob() method

C.   You must mark the subclass as final

D.   An abstract class cannot be extended, so you must change it to open

19: Your function is passed by a parameter obj of type Any. Which code snippet shows a way to retrieve the original type of obj, including package information?

A.   Obj.classInfo()

B.   Obj.typeInfo()

C.   Obj::class.simpleName

D.   Obj::class

20: Which is the correct declaration of an integer array with a size of 5?

A.   Val arrs[5]: Int

B.   Val arrs = IntArray(5)

C.   Val arrs: Int[5]

D.   Val arrs = Array(5)

21: You have created a class that should be visible only to the other code in its module. Which modifier do you use?

A.   Internal

B.   Private

C.   Public

D.   Protected

22: Kotlin has two equality operators, == and ===. What is the difference?

A.   == determines if two primitive types are identical. === determines if two objects are identical

B.   == determines if two references point to the same object. === determines if two objects have the same value

C.   == determines if two objects have the same value. === determines if two strings have the same value

D.   == determines if two objects have the same value. === determines if two references point to the same object

23: Which snippet correctly shows setting the variable max to whichever variable holds the greatest value, a or b, using idiomatic Kotlin?

A.   Val max3 = a.max(b) (Extension Function is One of the idiomatic Solutions in Kotlin)

B.   Val max = a > b ? a : b

C.   Val max = if (a > b) a else b

D.   If (a > b) max = a else max = b

24: You have an enum class Signal that represents the state of a network connection. You want to print the position number of the SENDING enum. Which line of code does that?

A.   Enum class Signal { OPEN, CLOSED, SENDING }

B.   Println(Signal.SENDING.position())

C.   Println(Signal.SENDING.hashCode())

D.   Println(Signal.SENDING)

E.   Println(Signal.SENDING.ordinal)

25: You would like to know each time a class property is updated. Which code snippet shows a built-in delegated property that can accomplish this?

A.   Delegates.watcher()

B.   Delegates.observable()

C.   Delegates.rx()

D.   Delegates.observer()

26: What is the correct way to initialize a nullable variable?

A.   Val name = null

B.   Var name: String

C.   Val name: String

D.   Val name: String? = null

27: Which line of code is a shorter, more idiomatic version of the displayed snippet? val len: Int = if (x != null) x.length else -1

A.   Val len = x?.let{x.len} else {-1}

B.   Val len = x!!.length ?: -1

C.   Val len:Int = (x != null)? x.length : -1

D.   Val len = x?.length ?: -1

28: The Kotlin .. operator can be written as which function?

A.   A.from(b)

B.   A.range(b)

C.   A.rangeTo(b)

D.   A.to(b)

29: In this code snippet, why does the compiler not allow the value of y to change? For(y in 1..100) y+=2

A.   Y must be declared with var to be mutable

B.   Y is an implicitly immutable value

C.   Y can change only in a while loop

D.   In order to change y, it must be declared outside of the loop

30: This code snippet compiles without error, but never prints the results when executed. What could be wrong? Val result = generateSequence(1) { it + 1 }.toList(); Println(result)

A.   The sequence lacks a terminal operation.

B.   The sequence is infinite and lacks an intermediate operation to make it finite.

C.   The expression should begin with generateSequence(0).

D.   The it parameter should be replaced with this.

31: You would like to group a list of students by last name and get the total number of groups. Which line of code accomplishes this, assuming you have a list of the Student data class? Data class Student(val firstName: String, val lastName: String)

A.   Println(students.groupBy{ it.lastName }.count())

B.   Println(students.groupBy{ it.lastName.first() }.fold().count())

C.   Println(students.groupingBy{ it.lastName.first() }.count())

D.   Println(students.groupingBy{ it.lastName.first() }.size())

32: You have an unordered list of high scores. Which is the simple method to sort the highScores in descending order? fun main() { val highScores = listOf(4000, 2000, 10200, 12000, 9030)}

A.   .sortedByDescending()

B.   .descending()

C.   .sortedDescending()

D.   .sort(

33: Your class has a property name that gets assigned later. You do not want it to be a nullable type. Using a delegate, how should you declare it?

A.   Lateinit var name: String // lateinit is modifier not delegate

B.   Var name: String by lazy

C.   Var name: String by Delegates.notNull()

D.   Var name: String? = null

34: You want to know each time a class property is updated. If the new value is not within range, you want to stop the update. Which code snippet shows a built-in delegated property that can accomplish this?

A.   Delegates.vetoable()

B.   Delegates.cancellable()

C.   Delegates.observer()

D.   Delegates.watcher()

35: Which line of code shows how to call a Fibonacci function, bypass the first three elements, grab the next six, and sort the elements in descending order?

A.   Val sorted = fibonacci().skip(3).take(6).sortedDescending().toList()

B.   Val sorted = fibonacci().skip(3).take(6).sortedByDescending().toList()

C.   Val sorted = fibonacci().skip(3).limit(6).sortedByDescending().toList()

D.   Val sorted = fibonacci().drop(3).take(6).sortedDescending().toList()

36: You have two arrays, a and b. Which line combines a and b as a list containing the contents of both? val a = arrayOf(1, 2, 3) val b = arrayOf(100, 200, 3000)

A.   Val c = list of (a, b)

B.   Val c = a + b

C.   Val c = listOf(a+b)

D.   Val c = listOf(*a, *b)

37: This code is occasionally throwing a null pointer exception (NPE). How can you change the code so it never throws as NPE? println("length of First Name = ${firstName!!.length}")

A.   Replace !!. with ?.

B.   Replace !!. with ?:.

C.   Surround the line with a try/catch block.

D.   Replace !!. with ?.let.

38: What is the execution order of init blocks and properties during initialization?

A.   All of the properties are executed in order of appearance, and then the init blocks are executed.

B.   The init blocks and properties are executed in the same order they appear in the code.

C.   All of the init blocks are executed in order of appearance, and then the properties are executed.

D.   The order of execution is not guaranteed, so code should be written accordingly.

39: What are the two ways to make a coroutine's computation code cancellable?

A.   Call the yield() function or check the isActive property.

B.   Call the cancelled() function or check the isActive property.

C.   Call the stillActive() function or check the isCancelled property.

D.   Call the checkCancelled() function or check the isCancelled property.

40: Which statement declares a variable mileage whose value never changes and is inferred to be an integer?

A.   Val mileage:Int = 566

B.   Var mileage:Int = 566

C.   Val mileage = 566 (Note: inferred)

D.   Const int mileage = 566

41: What is the preferred way to create an immutable variable of type long?

A.   Var longInt = 10L

B.   Const long longInt = 10

C.   Val longInt = 10L

D.   Val longInt:Long = 10

42: Which line converts the binaryStr, whish contain only 0s and 1s, to an integer representing its decimal value? val binaryStr = "00001111"

A.   Val myInt = toInt(binaryStr)

B.   Val myInt = binaryStr.toInt(

C.   Val myInt = binaryStr.toInt()

D.   Val myInt = binaryStr.toInt(2)

43: In a Kotlin program, which lines can be marked with a label

A.   Any program line can be marked with a label

B.   Any statement can be marked with a label

C.   Any expression can be marked with a label

D.   Only the beginning of loops can be marked with a label

44: All classes in Kotlin inherit from which superclass?

A.   Default

B.   Super

C.   Any

D.   Object

45: You have written a function, sort(), that should accept only collections that implement the Comparable interface. How can you restrict the function? fun sort(list: List): List { return list.sorted()}

A.   Add Comparable> between the fun keyword and the function name

B.   Add Comparable between the fun keyword and the function name

C.   Add > between the fun keyword and the function name

D.   Add > between the fun keyword and the function name

46: Kotlin classes are final by default. What does final mean?

A.   Final means that you cannot use interfaces with this class.

B.   Final means that this is the only file that can use the class.

C.   Final means that you cannot extend the class.

D.   Final classes cannot be used in the finally section of a try/catch block.

47: You have created an array to hold three strings. When you run the code bellow, the compiler displays an error. Why does the code fail? val names = arrayOf(3) names[3]= "Delta"

A.   Arrays use zero-based indexes. The value 3 is outside of the array's bounds

B.   You accessed the element with an index but should have used.set().

C.   You declared the array with val but should have used var

D.   You cannot changes the value of an element of an array. You should have used a mutable list.

48: If a class has one or more secondary constructors, what must each of them do?

A.   Each secondary constructor must call super().

B.   Each secondary constructor must call base().

C.   Each secondary constructor must directly or indirectly delegate to the primary.

D.   Each secondary constructor must have the same name as the class.

49: When you can omit constructor keyword from the primary constructor?

A.   It can be omitted only if an init block is defined.

B.   It can be omitted anytime; it is not mandatory.

C.   It can be omitted if secondary constructors are defined.

D.   It can be omitted when the primary constructor does not have any modifiers or annotations.

50: How many different kinds of constructors are available for kotlin classes?

A.   Two.

B.   None.

C.   Four.

D.   One.