Kotlin Interview question

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

How do Lambda Functions Work in Kotlin?

A lambda function is a small, self-contained block of code that can be passed around your program for greater flexibility. They're usually written inline and solve basic but frequent programming tasks. fun main(args: Array<String>) { val greet = { println("Hello!")} // first lambda function greet() val product = { x: Int, y: Int -> x * y } // second lambda function val result = product(3, 5) println("Product of two numbers: $result") } The first lambda greets the user with the text "Hello" while the second one returns the product of two numbers. Lambda functions are anonymous, meaning they don't have any names.

Explain the Class Modifiers in Kotlin

Class modifiers allow developers to customize their class declarations as they need it. We're demonstrating the four modifiers Kotlin exposes to programmers for this purpose. private - the class declaration is only visible inside the file that contains it public - these class declarations are visible everywhere, it's the default in Kotlin protected - makes the class unavailable for top-level Kotlin declarations internal - makes the declaration available for all the same modules

Explain Why the Following Code Fails to Compile class A{ } class B : A(){ }

Classes in Kotlin are final by default. So, you can not inherit the attributes of the first class A from the second class B. You will need to declare the first class as open for solving this issue. The below snippet will illustrate this for you. open class A{ } class B : A(){ }

What is Any, Unit, and Nothing?

In Kotlin, any is a data type that represents basic types like integer, floats, and strings. Any type can not hold any null values by default and implements automatic casting of lower types. This is similar to the Java object java.Lang.Object. The unit type is a type that is returned by function calls that don't return anything. Kotlin doesn't offer void functions like C or Java do and utilizes unit for this purpose. You can think of unit as nothing but one specific instance. The nothing type is returned by Kotlin functions when they can't reach the bottom of the function. It usually happens due to infinite loops or recursions.

Describe For Loops in Kotlin

In Kotlin, for loop is used to iterate through the following because all of them provides iterator. Range Array String Collection val sports = listOf("cricket", "football", "basketball") for (sport in sports) { println("Let's play $sport!") }

Explain the Workings of when in Kotlin

In Kotlin, when replaces the switch operator of other languages like Java. A certain block of code needs to be executed when some condition is fulfilled. The argument of when expression compares with all the branches one by one until some match is found. After the first match found, it reaches to end of the when block and execute the code next to when block. Unlike switch case in java or any other programming language, we do not require break statement at the end of each case. In Kotlin, when can be used in two ways: when as a statement We can use when as a statement without else branch. If it is used as a statement, the values of all individual branches are compared sequentially with the argument and execute the corresponding branch where condition matches. If none of the branches satisfied with the condition then it simply exits the block without printing anything to system output. when as an expression If it is used as an expression, the value of the branch with which condition satisfied will be the value of overall expression. As an expression when returns a value with which the argument matches and we can store it in a variable or print directly.

Write a Kotlin Program for Calculating the Power of a Number

It is based on recursion. fun main(args: Array<String>) { print("Enter the base:") val base = readLine()!!.toInt() print("Enter the power:") val power = readLine()!!.toInt() val result = powerRaised(base, power) println("$base^$power = $result") } fun powerRaised(base: Int, power: Int): Int { if (power != 0) return base * powerRaised(base, power - 1) else return 1 }

How to Migrate Java Code to Kotlin?

It's possible for us to migrate existing Java codes to Kotlin easily using the IntelliJ IDEA from JetBrains. Update the build file to support Kotlin compilation Open the necessary .java file using IDEA Copy all the required code snippets Create a Kotlin file ending with .kt Paste the code snippets in this Kotlin file Enter Yes when IDEA asks if it should convert the Java code to Kotlin

Is Kotlin better than Java?

Java is still a better language for building enterprise-grade consumer applications due to its massive feature list and unending community support. However, despite being a new language, Kotlin interoperates nicely with Java. It allows developers to create innovative applications without writing hundreds of lines of code. Kotlin's strong type inferences make it a solid choice for developing next-generation apps. Moreover, since it can be also used for developing iOS apps, developers don't need to embrace new stacks anymore.

What Extension Methods does Kotlin provide to java.io.File?

Java uses the java.io.File class for providing abstract representations of file or directory paths. Kotlin offers the below extension methods to this file - bufferedReader() - allows to read the contents of a file and put them into a buffer readBytes() - can be used for reading the contents of a file into a ByteArray readText() - allows reading file contents and puts them to a String forEachLine() - reads a file line by line readLines() - line by line reads a file and puts them into a List

What are Co-Routines in Kotlin?

Kotlin aims at increasing app performance via leveraging asynchronous execution. Contrary to traditional execution flows, asynchronous executions don't get blocked on I/O. It makes Kotlin ideal for building large-scale IT infrastructures. Take a look at the below example to understand co-routines more clearly. import kotlinx.coroutines.* fun main() { GlobalScope.launch { // creates a new coroutine and continues delay(2000L) // non-blocking delay for 2000 milliseconds or 2 sec. println("Hello") } println("World!") // execution continues even while coroutine waits Thread.sleep(4000L) // block main thread for 4 seconds } This program will display the string "World!" before displaying "Hello". The program first creates a new coroutine within the GlobalScope and wait for 2 seconds. Meanwhile, the main thread will continue and print "World!". It will wait for 4 seconds then and after two seconds, the coroutine will print "Hello".

How do Destructuring Declarations Work in Kotlin?

Kotlin allows developers to assign multiple values to variables from data stored in objects or arrays. data class Book(val name: String, val publication: String){ } fun main(args: Array<String>) { val (name, publication) = Book("Kotlin for Dummies", "O'Reilly") println(name) println(publication) } When compiled, this program will return the name and publication of the book from the specified data class. The destructuring takes place in the first line inside the main function.

How to Create Arrays of Different Types in Kotlin

Kotlin allows programmers to easily create different types of arrays using the arrayOf() method. Arrays can contain integer, floats, and strings using this simple but robust procedure. val arr1 = arrayOf(1, 2, 3) val arr2 = arrayOf(1.2, 2.3, 3.4) val arr3 = arrayOf("Hello", "String", "Array)

Differentiate between Kotlin's Variable Declaration Methods

Kotlin allows you to declare variables in two different ways. It exposes the val and var keyword for this purpose. Kotlin doesn't allow users to change the value of variables that were created using the val keyword.

What is Null Safety in Kotlin?

Kotlin comes with in-built protection against unwanted null references which allows it to be more fault-tolerant. It thus allows programs to reduce NullPointerExceptions during runtime and prevents unwanted program crashes.

Explain the Fundamental Data Types of Kotlin

Kotlin data types define the procedures available on some data. The compiler allocates memory space for variables using their data type. integers - available integer types are Long represents a 64-bit signed integer Int represents a 32-bit signed integer, Short represents a 16-bit signed integer, and Byte represents a 8-bit signed integer floats - floating-point values contain fractional values; they can be declared using Float represents a 64-bit signed integer or Double represents a 32-bit signed integer characters - represented by the Char modifier; usually hold a single Unicode character strings - they are created using the String type and are immutable like in Java booleans - represents the boolean values true and false arrays - arrays in Kotlin are represented using the Array class

Why Doesn't Kotlin Feature Explicit Ternary Conditionals?

Kotlin doesn't offer any specific ternary operator of the form c = (a < b) ? a : b; like Java or C. It omits this option because you can do the same with the if expression in Kotlin. Since the above ternary operator is essentially an expression of the form (condition ? then : else), Kotlin simply allows you to do this using its standard if keyword. val c = if (a < b) a else b This line of code does the same thing in Kotlin as the ternary operator does in Java. You can also pack blocks inside if-else branches.

Describe Kotlin's Interoperability with JavaScript

Kotlin enables Android and iOS devs to seamlessly target JavaScript. What this means is, you can easily trans-compile a program written in Kotlin to native JavaScript code. This allows developers to easily create software for the popular Node.JS platform. Kotlin enables developers to control all elements of JS programming- such as manipulating the DOM, leveraging graphics, managing the server-side, and so on. Additionally, you can utilize Kotlin with existing JS libraries like jQuery, and React.

Explain the Structural Expressions of Kotlin

Kotlin has three different structural expressions - return, break, and continue. return - this expression halts the program execution and returns from the enclosing function break - it is used for terminating the nearest enclosing loop in Kotlin continue - it allows the execution to proceed to the next iteration without performing the current operation.

What is Kotlin?

Kotlin is a robust programming language developed to run on top of the JVM(Java Virtual Machine). It is developed by Jetbrains, a popular IT company famous for building top-quality development tools. Kotlin is statically typed and offers exceptional support for functional programming. Additionally, Kotlin addresses some glaring issues faced by many Java programmers such as null-based errors. It can be used for developing both Android and iOS apps alongside general-purpose software. Due to its extreme compatibility with Java, developers can write new features for their Java-based applications directly in Kotlin.

What are the Kotlin Data Classes?

Kotlin offers a convenient way of storing values by means of the data class. A data class comes with many useful in-built methods such as for copying, string representations, instance collections, and so on. Data classes are defined using the data modifier. Some auto-generated methods available to a newly created data class are - toString, equals, copy, hashCode, and componentN functions. The first method returns a string representation, equals check for equality among properties, and copy allows cloning.

What's the Difference Between const and val?

Kotlin offers the const keyword for creating constants. The key difference between val and const is their execution phase. Kotlin sets the properties of val at runtime by default. On the other hand, const is set by the compiler during the program's compiler time. const val str = "Fixed string!" // global variable fun main(args: Array<String>) { const val x = 4 const val str = "New string.." // local variable } Additionally, you can not use const inside the local scope, thus the above code block will fail to compile. This modifier is also not applicable on var.

Explain the Different Constructors in Kotlin

Kotlin offers two different constructors for initializing class attributes. Primary Constructor - resides in the class declaration header Secondary Constructor - declared inside Kotlin class body and may have multiple instances.

What is the Purpose of Object Keyword?

Kotlin provides an additional keyword called object alongside its standard object-oriented features. Contrary to the traditional object-oriented paradigm where you define a class and create as many of its instances as you require, the object keyword allows you to create a single, lazy instance. The compiler will create this object when you access it in your Kotlin program. The following program provides a simple illustration. fun calcRent(normalRent: Int, holidayRent: Int): Unit { val rates = object{ var normal: Int = 30 * normalRent var holiday: Int = 30 * holidayRent } val total = rates.normal + rates.holiday print("Total Rent: $$total") } fun main() { calcRent(10, 2) }

Explain the Differences Between ? and !! in Terms of Null Safety

Kotlin provides two different mechanisms for unwrapping the contents of a nullable type. The Elvis operator '?' provides a safe call and doesn't crash your program if the content is of type null. However, on the other hand, !! is used for force unwrapping the contents of a nullable variable. This is performed during runtime and thus may lead to a potential system crash if the value returned is null. So, you should only use the !! modifier when you're certain about the value of your variables.

What is Nullability in Kotlin?

Kotlin's type system is aimed at eliminating the danger of null references from code. You'll need to define variables as nullable if you want it to contain null values. val name: String? = null This time, name can contain either String or null.

Why doesn't Kotlin Feature Macros?

Macros are useful in a number of programming scenarios. However, they tend to create a mess of your project and often confuse new developers. This is why JetBrains, the developers behind Kotlin omitted this feature altogether. Moreover, developers often find it hard to test or optimize codebases that contain a lot of macros. So, omitting macros is a design decision. Ther developers of Kotlin are, however, working on features like serialization and compiler plugins to address some shortcomings of this decision.

List Some Features of Kotlin that are Absent in Java

Null Safety - a flagship feature of Kotlin Co-Routines - enables asynchronous programming Operator Overloading - a key feature missing in Java Smart Casts - allows casting inferences Companion Object - another useful functionality

How do Ranges Work in Kotlin?

Ranges allow our programs to seamlessly iterate over a list or progression. In Kotlin, the range is a collection of finite values which is defined by endpoints. The range in Kotlin consists of a start, a stop, and the step. The start and stop are inclusive in the Range and the value of step is by default 1.The range is used with comparable types. There are three ways for creating Range in Kotlin - Using (..) operator Using rangeTo() function Using downTo() function

What are Kotlin Sealed Classes?

Sealed classes are another extremely useful feature of this modern-day programming language. They can be used to restrict the inheritance hierarchy of a class. All you need to do is define a class as sealed, and nobody will be able to create subclasses that belong to this sealed class. These classes will come in handy when you use them inside when expressions. If you can perfectly cover all possible cases, you won't have to use the else clause. However, remember that sealed classes are abstract by themselves and you can not instantiate one directly.

Why Use Kotlin in Mobile App Development?

Since Kotlin simplifies many syntactical elements of Java, it's easier to write concise, well-documented code. Additionally, since it runs directly on JVM, enterprises hardly need to invest in new tech stacks. So the cost-benefit adjustment is excellent. Moreover, Kotlin has already started to replace many Java-based Android apps, alongside iOS apps written in Swift. This number will only increase over time and adapting to Kotlin will become a must for modern enterprises.

What is Smart Casting in Kotlin?

Smart cast is a simple but useful mechanism that allows programmers to reduce most null-based errors. The Kotlin compiler does this by inferring the variables. simple example: fun test(a: Any) { if (a is String) { print(a.length) // a is cast to String by the compiler automatically } }

What are Kotlin's Best Features?

Some of Kotlin's best features are- It supports both object-oriented and functional programming paradigm. It provides easy to use lambda functions that are unavailable in Java. Maintaining Kotlin is considerably cheap and provides excellent fault-tolerance. Allows developing Node.js applications and JVMs. Great support for asynchronous communication. Exceptional compatibility with existing Java codes.

How do You Create Static Methods in Kotlin?

Static methods are useful for a number of reasons. They allow programmers to prevent the copying of methods and allow working with them without creating an object first. Kotlin doesn't feature the widely used static keyword found in Java. Rather, you'll need to create a companion object. class A { public static int returnMe() { return 5; } // Java } class A { companion object { fun a() : Int = 5 // Kotlin } }

How do String Interpolations Work in Kotlin?

String interpolations work with multiple placeholders and first evaluate their value to display the final string output. This final output will contain the corresponding values of the placeholders. The below code snippet will illustrate a simple example of Kotlin string interpolation. fun main(args: Array<String>) { // String Interpolation print("Please enter your name here:") val name:String? = readLine() print("Hello, $name!") } Here, the Kotlin compiler first receives the user input and interpolates this value in place of the placeholder $name. The last line of the snippet is translated by the compiler as shown below - new StringBuilder().append("Hello, ").append(name).append("!").toString()

Write a Program to Swap Two Numbers Without Using Temporary Variables

Take a look at the below Kotlin program to find out how to do this in action. fun main(a: Array<String>) { var variable1 = 10 var variable2 = 20 println("Before swapping:") println("First variable has: $variable1") println("Second variable has: $variable2") variable1 = variable1 + variable2 variable2 = variable1 - variable2 variable1 = variable1 - variable2 println("After swapping:") println("First variable contains: $variable1") println("Second variable contains: $variable2") }

What is the Function of the Elvis Operator?

The Elvis operator in Kotlin allows app developers to handle null-based exceptions. It is a compelling feature of Kotlin which enables programmers to reduce runtime crashes by a considerable margin. Although you can still handle your nulls yourself, the Elvis operator makes it relatively straightforward. val z = x ?: return y In this line, z will only contain the value of x if it is not null. Otherwise, the entire expression will halt executing and return y. It works since the return statement is also an expression. So, Elvis operator's look like a ?: b in Kotlin.

What's the Problem with Below Code? val name = "UBUNTU" val upperCase = name.toUpperCase() name.inc()

The above code snippet will fail to compile due to type exception. Kotlin is statically typed and implements strong type inferences. Since the value of the name variable is a String, Kotlin assumes that name is also a type of String. Thus the second line is perfectly valid because the method toUpperCase() is a String method. The last line, however, tries to perform an increment operation. This line causes Kotlin to throw a compilation error since inc() can only work with Int values, not Strings.

What's the Entry Point for Kotlin Programs?

The main() function is this point, similar to other OOP languages such as C++ and Java. Developers can easily define the command-line arguments taken by Kotlin programs. For this, you'll need to pass args: Array<String> to this main() function.

What is Kotlin Multiplatform?

The multiplatform feature enables programmers to share code between several platforms such as JavaScript, iOS, and desktop apps. It reduces the amount of code by a considerable factor. You can use much of the same codebase for writing apps for different platforms thanks to this feature. Simply create a shared module for your apps and list the dependencies. Now, you can create separate modules for different platforms and integrate the core functionalities using the common module.

Describe While and Do-While Loops

The while and do-while loops work quite similar but have a specific distinction. The do-while loop executes at least once, even if the first conditional expression is returned as false. Contrary to this, while loops will stop execution if the loop isn't true at a given time. var i = 1 while (i < 5) { // while loop println(i) i++ } This code will print the numbers 1 to 4 and then terminate. Now, take a look at the below do-while snippet. var i = 6 do{ // do-while println(i) i++ }while(i<5) Although the condition to while is false, it will print the number 6 as its output. This happens since the execution of the do block takes place without checking the condition first.

How to Create Volatile Variables?

Volatile variables are a compelling feature that enables programmers to control threads, and CPU time more effectively. Declaring a variable as volatile is quite easy and differs slightly than from Java. @Volatile var name:String = "something" Actually, volatile is not a keyword in Kotlin, as opposed to Java. Rather it is an annotation and makes each data write visible to all other threads immediately.

Is It Possible to Execute Kotlin Code without JVM?

Yes, it is. Developers can use the Kotlin/Native tool for doing this effortlessly. It's an effective LLVM backend that allows us to create standalone executables. It exposes some additional functionalities as well.

Does Kotlin Allow Calling Java Functions?

Yes, it is. Functions such as the getter and setter duo are represented as properties. Kotlin assigns Unit to each void value that comes from a Java function. Thus, the Unit in Kotlin is simply void in Java code. Since keywords like is, in, and object are valid identifiers in Java, you'll need to escape them in Java libraries using the backtick (`) character. Additionally, Kotlin implements features like platform types and annotations to ensure null safety when calling external Java functions.

How to Compare Two Strings in Kotlin?

You can use the equality operator '==' or compareTo() function for comparing strings in Kotlin.

Write a Program for Finding the Sum of Natural Numbers

fun main( args: Array<String> ) { print("Enter the number:") var num = readLine()!!.toIntOrNull() var sum = 0 // inital value of summation if( num != null ){ for (i in 1..num) { sum += i } println("Sum = $sum") } }

Write a Program for Determining if a Number is Prime or Not

fun main( args: Array<String> ) { print("Enter the number:") var num = readLine()!!.toIntOrNull() var flag = false if( num != null ){ for (i in 2..num / 2) { if (num % i == 0) { flag = true break } } } if (flag) println("$num is not a prime number.") else println("$num is a prime number.") }

How to Convert Strings to Integer?

fun main(args: Array<String>) { for (string in args) { try { val parsedValue = string.toInt() println("The parsed integer value is $parsedInt") } catch (nfe: NumberFormatException) { // not a valid int } } } You can also do this without using explicit try-catch blocks. For this, you'll need to utilize the toIntOrNull() method.

Find Factorial of Numbers using Recursion

fun main(args: Array<String>) { print("Enter the number:") val number = readLine()?.toInt() if(number != null ){ val factorial = multiplyNums(number) println("Factorial of $number = $factorial") } } fun multiplyNums(number: Int): Long { if (number >= 1) ,return number * multiplyNums(number - 1) // recursive call to multiplyNums else return 1 }

Write a Kotlin Program to Display the Fibonacci Series

fun main(args: Array<String>) { val range = 10 var firstNumber = 0 var secondNumber = 1 print("First $range numbers of Fibonacci series: ") for (i in 1..range) { print("$firstNumber + ") val sum = firstNumber + secondNumber firstNumber = secondNumber secondNumber = sum } }


Ensembles d'études connexes

HEALTH AND LIFESTYLE 101: Chapters 1-3 and 5 Questions and Answers

View Set

Ponce de Leon FL's First Spanish Explorer

View Set

Chapter 21: cancer development NCLEX questions

View Set

Module 7: The History Of The Computer

View Set

principles of management midterm

View Set

Data Structures & Algorithms - Chapter 7 & 11 QUIZ

View Set

Patient Protection and Affordable Care Act (PPACA) - Section 14 - Quiz

View Set