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

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 ad abstract classes are very similar. What is one thing abstract class can do that interfaces cannot?

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

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
}

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

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
}

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

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

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?

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

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

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

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

Q16. What value is printed by println()?

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

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 ae 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(_____)

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

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

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?

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

class Employee
class Manager : Employee()

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

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()")
  }
}

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()
}

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)

Q27. What three methods does this class have?

class Person

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

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

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

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?

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

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

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

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 }

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"
  }
}

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"
  }
}

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?

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

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"
  }
}

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++
}

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

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

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

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

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