linkedin-skill-assessments-quizzes

Kotlin

Q1. You would like to print each score on its own line with its cardinal position. Without using var or val, which method allows iteration with both the value and its position?

fun main() {
  val highScores = listOf(4000, 2000, 10200, 12000, 9030)
}

reference

Q2. When the Airplane class is instantiated, it displays Aircraft = null, not Aircraft = C130 why?

abstract class Aircraft {
  init { println("Aircraft = ${getName()}") }
  abstract fun getName(): String
}
class Airplane(private val name: String) : Aircraft() {
  override fun getName(): String = name
}

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

reference

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

reference

Q5. Your application has an add function. How could you use its invoke methods and display the results?

fun add(a: Int, b: Int): Int {
  return a + b
}

reference

Q6. What is the entry point for a Kotlin application?

Q7. 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

reference

Q8. You pass an integer to a function expecting type Any. It works without issue. Why is a primitive integer able to work with a function that expects an object?

fun showHashCode(obj: Any){
  println("${obj.hasCode()}")
}
fun main() {
  showHashCode(1)
}

Q9. 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
}

reference

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

reference

Q11. You have written a snippet of code to display the results of the roll of a six-sided die. When the die displays from 3 to 6 inclusive, you want to display a special message. Using a Kotlin range, what code should you add?

when (die) {
  1 -> println("die is 1")
  2 -> println("die is 2")
  ___ -> printlin("die is between 3 and 6")
  else -> printlin("dies is unknown")
}

reference

Q12. 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?

reference

Q13. This code does not print any output to the console. What is wrong?

firstName?.let {
  println("Greeting $firstname!")
}

reference

Q14. You have a function simple() that is called frequently in your code. You place the inline prefix on the function. What effect does it have on the code?

inline fun simple(x: Int): Int{
  return x * x
}

fun main() {
  for(count in 1..1000) {
    simple(count)
  }
}

reference

Q15. How do you fill in the blank below to display all of the even numbers from 1 to 10 with least amount of code?

for (_____) {
  println("There are $count butterflies.")
}

reference

Q16. What value is printed by println()?

val set = setOf("apple", "pear", "orange", "apple")
println(set.count())

reference

Q17. Which line of code shows how to display a nullable string’s length and shows 0 instead of null?

Q18. 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(_____)

reference

Q19. Which code snippet correctly shows a for loop using a range to display “1 2 3 4 5 6”?

reference

Q20. You are upgrading a Java class to Kotlin. What should you use to replace the Java class’s static fields?

reference

Q21. 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?

reference

Q22. Kotlin will not compile this code snippet. What is wrong?

class Employee
class Manager : Employee()

reference

Q23. Which function changes the value of the element at the current iterator location?

reference

Q24. From the Supervisor subclass, how do you call the Employee class’s display() method?

open class Employee(){
  open fun display() = println("Employee display()")
}
class Supervisor : Employee() {
  override fun display() {
    println("Supervisor display()")
  }
}

reference

Q25. The code below compiled and executed without issue before the addition of the line declaring errorStatus. Why does this line break the code?

sealed class Status(){
  object Error : Status()
  class Success : Status()
}
fun main(){
  var successStatus = Status.Success()
  var errorStatus = Status.Error()
}

reference

Q26. The code below is expected to display the numbers from 1 to 10, but it does not. Why?

val seq = sequence { yieldAll(1..20) }
  .filter { it < 11 }
  println(seq)

reference

Q27. What three methods does this class have?

class Person

reference

Q28. Which is the proper way to declare a singleton named DatabaseManager?

reference

Q29. 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)
}

reference

Q30. The code snippet below translates a database user to a model user. Because their names are both User, you must use their fully qualified names, which is cumbersome. You do not have access to either of the imported classes’ source code. How can you shorten the type names?

import com.tekadept.app.model.User
import com.tekadept.app.database.User

class UserService{
  fun translateUser(user: com.tekadept.app.database.User): User =
    com.tekadept.app.model.User("${user.first} ${user.last}")
}

reference

Q31. 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?

reference

Q32. Which is the correct declaration of an integer array with a size of 5?

reference

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

reference

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

reference

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

Q36. 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?

enum class Signal { OPEN, CLOSED, SENDING }

reference

Q37. Both const and @JvmField create constants. What can const do that @JvmField cannot?

class Detail {
  companion object {
    const val COLOR = "Blue"
    @JvmField val SIZE = "Really Big"
  }
}

reference

Q38. You have a when expression for all of the subclasses of the class Attribute. To satisfy the when, you must include an else clause. Unfortunately, whenever a new subclass is added, it returns unknown. You would prefer to remove the else clause so the compiler generates an error for unknown subtypes. What is one simple thing you can do to achieve this?

open class Attribute
class Href: Attribute()
class Src: Attribute()
class Alt: Attribute()

fun getAttribute(attribute: Attribute) : String {
  return when (attribute) {
    is Href -> "href"
    is Alt -> "alt"
    is Src -> "src"
    else -> "unknown"
  }
}

reference

Q39. 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?

reference

Q40. Why doesn’t this code compile?

val addend = 1
infix fun Int.add(added: Int=1) = this + addend
fun main(){
  val msg = "Hello"
  println( msg shouldMatch "Hello")
  println( 10 multiply 5 + 2)
  println( 10 add 5)
}

reference

Q41. What is the correct way to initialize a nullable variable?

Q42. Which line of code is a shorter, more idiomatic version of the displayed snippet?

val len: Int = if (x != null) x.length else -1

Q43. You are creating a Kotlin unit test library. What else should you add to make the following code compile without error?

fun String.shouldEqual(value: String) = this == value
fun main(){
  val msg = "test message"
  println(msg shouldEqual "test message")
}

Q44. What is the difference between the declarations of COLOR and SIZE?

class Record{
  companion object {
    const val COLOR = "Red"
    val SIZE = "Large"
  }
}

reference

Q45. Why does not this code snippet compile?

class Cat (name: String) {
  fun greet() { println("Hello ${this.name}") }
}

fun main() {
  val thunderCat = Cat("ThunderCat")
  thunderCat.greet()
}

Q46. The code below shows a typical way to show both index and value in many languages, including Kotlin. Which line of code shows a way to get both index and value more idiomatically?

var ndx = 0;
for (value in 1..5){
  println("$ndx - $value")
  ndx++
}

reference

Q47. The Kotlin .. operator can be written as which function?

reference

Q48. How can you retrieve the value of the property codeName without referring to it by name or destructuring?

data class Project(var codeName: String, var version: String)
fun main(){
  val proj = Project("Chilli Pepper", "2.1.0")
}

reference

Q49. This function generates Fibonacci sequence. Which function is missing?

fun fibonacci() = sequence {
  var params = Pair(0, 1)
  while (true) {
    ___(params.first)
    params = Pair(params.second, params.first + params.second)
  }
}

reference

Q50. In this code snippet, why does the compiler not allow the value of y to change?

for(y in 1..100) y+=2

Q51. You have created a data class, Point, that holds two properties, x and y, representing a point on a grid. You want to use the hash symbol for subtraction on the Point class, but the code as shown will not compile. How can you fix it?

data class Point(val x: Int, val y: Int)

operator fun Point.plus(other: Point) = Point(x + other.x, y + other.y)
operator fun Point.hash(other: Point) = Point(x - other.x, y - other.y)

fun main() {
    val point1 = Point(10, 20)
    val point2 = Point(20, 30)
    println(point1 + point2)
    println(point1 # point2)
}

Q52. 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)

reference

Q53. An error is generated when you try to compile the following code. How should you change the call to printStudents to fix the error?

fun main() {
    val students = arrayOf("Abel", "Bill", "Cindy", "Darla")
    printStudents(students)
}

fun printStudents(vararg students: String) {
    for(student in students) println(student)
}

Q54. Both y and z are immutable references pointing to fixed-size collections of the same four integers. Are there any differences?

val y = arrayOf(10, 20, 30, 40)
val z = listOf(10, 20, 30, 40)

Q55. The code snippet compile and runs without issue, but does not wait for the coroutine to show the “there” message. Which line of code will cause the code to wait for the coroutine to finish before exiting?

fun main() = runBlocking {
    val task = GlobalScope.launch {
        delay(1000L)
        println("there")
    }
    println("Hello,")
}

Q56. 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)

Q57. Class BB inherits from class AA. BB uses a different method to calculate the price. As shown, the code does not compile. What changes is needed to resolve the compilation error?

open class AA() {
     var price: Int = 0
        get() = field + 10
}
class BB() : AA() {
     var price: Int = 0
        get() = field + 20
}

Q58. What is the output of this code?

val quote = "The eagle has landed."
println("The length of the quote is $quote.length")

Q59. 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)

Q60. 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?

Q61. 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?

Q62. 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?

reference

Q63. 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)

Q64. 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}")

reference

Q65. What is the execution order of init blocks and properties during initialization?

reference

Q66. Both const and @JvmField create constants. What can @JvmField do that const cannot?

class Styles {
  companion object {
    const val COLOR = "Blue"
      @JvmField val SIZE = "Really big"
   }
}

reference

Q67. What are the two ways to make a coroutine’s computation code cancellable?

reference

Q68. Given the code below, how can you write the line this.moveTo(“LA”) more concisely?

data class Student (val name: String, var location: String) {
  fun moveTo (newLoc: String) { location = newLoc }

}

fun main() {

  Student ("Snow", "Cologne").run {

  this.moveTo ("LA")

}

Q69. For the Product class you are designing, you would like the price to be readable by anyone, but changeable only from within the class. Which property declaration implements your design?

var price: Int = 0
  public get()
  private set
var price: Int = 0
  private set
var price: Int = 0
  val set
val price: Int=0

Q70. What will happen when you try to build and run this code snippet?

class SpecialFunction : () -> Unit {
  override fun invoke() {
    println("Invoked from an instance.")
  }
}
fun main() {
  try { SpecialFunction()() }
  catch (ex: Exception) { println("An error occurred") }
}

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

Q72. What is the preferred way to create an immutable variable of type long?

Q73. Which line converts the binaryStr, whish contain only 0s and 1s, to an integer representing its decimal value?

val binaryStr = "00001111"

Q74. In a Kotlin program, which lines can be marked with a label

  1. article -
  2. reference

Q75. All classes in Kotlin inherit from which superclass?

reference

Q76. 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<T>): List <T> {
    return list.sorted()
}

reference

Q77. Kotlin classes are final by default. What does final mean?

reference

Q78. 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<String>(3)
names[3]= "Delta"

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

reference

Q80. When you can omit constructor keyword from the primary constructor?

article - reference

Q81. How many different kinds of constructors are available for kotlin classes?

reference

Q82. What is the default visibility modifier in Kotlin?

reference

Q83. The code below compiles and executes without issue, but is not idiomatic kotlin. What is a better way to impelement the printlln()?

fun main() {
  val name: String = "Amos"
  val grade: Float = 95.5f
  println("My name is " + name + ". I score " + grade + " points on the last coding quiz.")
}

reference