Posts

Control flow based Kotlin interview questions and answers

if Expression 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. when Expression What is the equivalent of switch expression in Kotlin? How does it differ from switch? when is the equivalent of  switch  in  Kotlin . The default statement in a when is represented using the else statement. var num = 10 when (num) { 0. .4 -> print ( "value is 0" ) 5 -> print ( "value is 5" ) else -> { print ( "value is in neither of the abo...

String based Kotlin interview questions and answers

How does string interpolation work in Kotlin? Explain with a code snippet? String interpolation is used to evaluate string templates. We use the symbol $ to add variables inside a string. val name = "Journaldev.com" val desc = " $name  now has Kotlin Interview Questions too.  ${name.length} " Using  {}  we can compute an expression too How to compare two strings in Kotlin? Compares string in Kotlin are possible in the following ways: Using “==” operator: You can use ah operator for comparison of two string. In Kotlin == operator is used. Using compareTo() extension function Syntax of compareTo() function is given below : fun String.compareTo( other: String, ignoreCase: Boolean = false ): Int Another code example fun main(args: Array & lt; String & gt;) { val x: String = "Kotlin is  simple" val y: String = "Kotlin language is" + " easy" if (x == y) { println(" x and y are similar."...

OOPs based Kotlin interview questions and answers

Image
Class and Object: Is new a keyword in Kotlin? How would you instantiate a class object in Kotlin? NO . Unlike Java, in Kotlin, new isn’t a keyword. We can instantiate a class in the following way: class   A var a = A() val new = A() Tell me the default behavior of Kotlin classes? In Kotlin all classes are final by default. That’s because Kotlin allows multiple inheritances for classes, and an open class is more expensive than a final class. What are the class members in kotlin? Ans:  A class in kotlin have the following members: Initializer blocks Properties Open declarations Nested  classes Inner classes How do you define an object in Kotlin? To define an object in Kotlin, simply declare a class and instantiate it with the new keyword. This will create a new class instance, which can perform various actions. val newObject= object { val one = "Hello" val two = "World" override fun toString () = " $one $two " } The above would print “...