Functions based Kotlin interview questions and answers

Function


Kotlin Function

 What is the difference between a function and a method in Kotlin?

A function is a named code block invoked from other locations within the source code. A method is a function associated with an object and can be invoked from other code with the dot notation.

Kotlin functions are first-class functions that are easily stored in variables and data structures and can be pass as arguments and returned from other higher-order functions.

Sample function declaration and usage in Kotlin

fun double(x: Int): Int {
    return 2 * x
}
val result = double(2)
How many types are used in kotlin?
 
there are to type function used in kotlin:
1. Standard library function
2. User-defined function
 
What is the Standard library function and User-defined function?
 
1. A standard library function is built-in library functions that are implicitly present in the library and available for use.
2. A user-defined function is a function that is created by the user. User-defined function takes the parameters(s), perform an action and return the result of that action as a value
 

How is a function declared? Why are Kotlin functions known as top-level functions?
fun sumOf(a: Int, b: Int): Int{ return a + b }

A function’s return type is defined after the :
Functions in Kotlin can be declared at the root of the Kotlin file.

How do you declare a function in Kotlin?

To declare a function in Kotlin, use the fun keyword followed by the name of the function and the parameters that it accepts. You can then define the function body within curly braces.

16. How do you invoke a function in Kotlin?

To invoke a function in Kotlin, simply use its name followed by the parentheses operator and any necessary arguments. This will cause the function to execute with the specified arguments.


What is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE? What is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE?

Mid
Details

Explain what is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE?

fun printHello(name : String?) : Unit { 
   if (name != null) 
     print("Hello, $name!") 
   else 
     print("Hi there!") 
   // We don't need to write 'return Unit.VALUE' or 'return', although we could 
}
Solution

The purpose is the same as C's or Java's void. Only Unit is a proper type, so it can be passed as a generic argument etc.

  1. Why we don't call it "Void": because the word "void" means "nothing", and there's another type, Nothing, that means just "no value at all", i.e. the computation did not complete normally (looped forever or threw an exception). We could not afford the clash of meanings.

  2. Why Unit has a value (i.e. is not the same as Nothing): because generic code can work smoothly then. If you pass Unit for a generic parameter T, the code written for any T will expect an object, and there must be an object, the sole value of Unit.

  3. How to access that value of Unit: since it's a singleton object, just say Unit

  4. UNIT actually contains valuable information, it basically just means "DONE". It just returns the information to the caller, that the method has been finished.




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.


Aaaaaa

Kotlin Lambdas

What is a lambda expression in Kotlin?

A lambda expression is an anonymous function that can concisely represent a function with a single parameter. Lambda expressions are often used in conjunction with higher-order functions, such as map and filter.

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. We take a closer look at some simple Kotlin lambda functions to understand it in more detail.

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.

How do you create a lambda expression in Kotlin?

First, you must define the parameters the expression accepts using the parentheses operator. You can then provide an executable block of code within curly braces and use the arrow operator to indicate that this code is the body of the lambda expression.

val items = listOf(1, 2, 3, 4, 5)
items.fold(0, {
   acc: Int, i: Int ->
   print("acc = $acc, i = $i, ")
   val result = acc + i
   println("result = $result")
   result
})

To pass a lambda expression as an argument to a function, include it within parentheses after the function name and any necessary arguments. This will cause the code within that lambda expression to be executed whenever the function is called.25. How do you pass a lambda expression as an argument in Kotlin?

26. What is the difference between a lambda expression and an anonymous function?

A lambda expression is a function that can be passed as an argument to another function. An anonymous function is a function that does not have a name and cannot be passed as an argument to another function. Thus, they’re actually opposites.


aaaaaaaaaaaaaaaaaaa

Higher order Function

Higher-Order Functions: A higher-order function is a function that takes functions as parameters, or returns a function

Explain Higher-Order Functions?
 
Higher-Order Function is a function that takes functions as parameters or returns a function.

What are high order functions in Kotlin?

Kotlin supports higher-order function, that is functions can be passed as an argument to other functions or function can be returned as a value by a function. It is possible because Kotlin functions can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions.

Functions can be declared as Lambda statements and can be passed or returned.
      // lambda expression 
var lambda = {println("higher order function") } 
      // higher-order function 
fun higherfunc( lmbd: () -> Unit ) {    // accepting lambda as parameter 
   //statemnts
} 
fun main(args: Array) { 
     //invoke higher-order function 
    higherfunc(lambda)       // passing lambda as parameter 
}  

What are Higher-Order functions in Kotlin?

A higher-order function is a function that takes functions as parameters or returns a function. For example, A function can take functions as parameters.

fun passMeFunction(abc: () -> Unit) {
 // I can take function
 // do something here
 // execute the function
 abc()
}

For example, A function can return another function.

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

And, we have a function returnMeAddFunction which takes zero parameters and returns a function of the type ((Int, Int) -> Int).

fun returnMeAddFunction(): ((Int, Int) -> Int) {
 // can do something and return function as well
 // returning function
 return ::add
}

And to call the above function, we can do:

val add = returnMeAddFunction()
val result = add(2, 2)

Learn more about Higher-Order functions from MindOrks blog.


Aaaaaaaaa

Kotlin Inline Function

What are inline functions in Kotlin?

In case if you have a functioned without a class but on compile time Kotlin compiler converts the function, make a static object for it and then call that function by an anonymous class the anonymous instance which causes extra memory consumption. To come over it inline keyword is used, it copies the code into a class which is calling this method and our method behaves as a member of class calling it.

What is the Inline Function in Kotlin?
 
An inline function is declared with a keyword inline. The use of inline function enhances the performance of higher-order functions. The inline function tells the compiler to copy parameters and functions to the call site.

What is the difference between inline and infix functions? Give an example of each.

Inline functions are used to save us memory overhead by preventing object allocations for the anonymous functions/lambda expressions called. Instead, it provides that functions body to the function that calls it at runtime. This increases the bytecode size slightly but saves us a lot of memory.

kotlin interview questions inline functions

infix functions on the other are used to call functions without parentheses or brackets. Doing so, the code looks much more like a natural language.

kotlin interview questions infix notations


What is an inline function in Kotlin?

Inline function instruct compiler to insert complete body of the function wherever that function got used in the code. To use an Inline function, all you need to do is just add an inline keyword at the beginning of the function declaration.

Learn more about Inline functions from MindOrks blog.

 What is noinline in Kotlin?

While using an inline function and want to pass some lambda function and not all lambda function as inline, then you can explicitly tell the compiler which lambda it shouldn't inline.

inline fun doSomethingElse(abc: () -> Unit, noinline xyz: () -> Unit) {
 abc()
 xyz()
}

Learn more about noinline functions from MindOrks blog.

Infix function

What is an infix function in Kotlin?

An infix function is used to call the function without using any bracket or parenthesis. You need to use the infix keyword to use the infix function.

class Operations {
 var x = 10; 
 infix fun minus(num: Int) {
 	this.x = this.x - num
 } 
}
fun main() {
 val opr = Operations()
 opr minus 8
 print(opr.x)
}


Scope functions

Explain the use-case of let, run, with, also, apply in Kotlin.

Learn from MindOrks blog.What’s the difference between inline and infix functions? Give an example of each.

  • Inline functions are used to save us memory overhead by preventing object allocations for the anonymous functions/lambda expressions called. Instead, it provides that functions body to the function that calls it at runtime. This increases the bytecode size slightly but saves us a lot of memory.
  • Infix functions on the other are used to call functions without parentheses or brackets. Doing so, the code looks much more like a natural language.


What are scope functions in Kotlin? ☆☆☆

Answer: The Kotlin standard library contains several functions whose sole purpose is to execute a block of code within the context of an object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope. In this scope, you can access the object without its name. Such functions are called scope functions.

There are five of them:

  • let,
  • run,
  • with,
  • apply,
  • also.

Source: stackoverflow.com

Explain scope functions in the context of Kotlin. What are the different types of Scope functions available in Kotlin?

The Kotlin standard library includes numerous functions that aid in the execution of a block of code within the context of an object. When you use a lambda expression to call these functions on an object, temporary scope is created. These functions are referred to as Scope functions. The object of these functions can be accessed without knowing its name. Scope functions make code more clear, legible, and succinct, which are key qualities of the Kotlin programming language 

Following are the different types of Scope functions available in Kotlin:-

  • let:- 
    Context object:   it 
    Return value:   lambda result
    The let function is frequently used for null safety calls. For null safety, use the safe call operator(?.) with ‘let'. It only runs the block with a non-null value.
  • apply:-
    Context object:  this
    Return value:   context object
    “Apply these to the object,” as the name suggests. It can be used to operate on receiver object members, primarily to initialise them.
  • with:-
    Context object:  this
    Return value:   lambda result
    When calling functions on context objects without supplying the lambda result, ‘with' is recommended.
  • run:-
    Context object:  this 
    Return value:   lambda result
    The ‘run' function is a combination of the ‘let' and ‘with' functions. When the object lambda involves both initialization and computation of the return value, this is the method to use. We can use run to make null safety calls as well as other calculations.
  • also:-
    Context object:  it
    Return value:   context object
    It's used when we need to do additional operations after the object members have been initialised.

Explain scope functions in the context of Kotlin. What are the different types of Scope functions available in Kotlin?

The Kotlin standard library includes numerous functions that aid in the execution of a block of code within the context of an object. When you use a lambda expression to call these functions on an object, temporary scope is created. These functions are referred to as Scope functions. The object of these functions can be accessed without knowing its name. Scope functions make code more clear, legible, and succinct, which are key qualities of the Kotlin programming language.

Following are the different types of Scope functions available in Kotlin:-

  • let:- 
    Context object:   it 
    Return value:   lambda result
    The let function is frequently used for null safety calls. For null safety, use the safe call operator(?.) with ‘let'. It only runs the block with a non-null value.
  • apply:-
    Context object:  this
    Return value:   context object
    “Apply these to the object,” as the name suggests. It can be used to operate on receiver object members, primarily to initialise them.
  • with:-
    Context object:  this
    Return value:   lambda result
    When calling functions on context objects without supplying the lambda result, ‘with' is recommended.
  • run:-
    Context object:  this 
    Return value:   lambda result
    The ‘run' function is a combination of the ‘let' and ‘with' functions. When the object lambda involves both initialization and computation of the return value, this is the method to use. We can use run to make null safety calls as well as other calculations.
  • also:-
    Context object:  it
    Return value:   context object
    It's used when we need to do additional operations after the object members have been initialised.

aaaa


Extension Functions

Explain the use of extension functions?

Extension functions are beneficial for extending class without the need to inherit from the class.

What do you understand about function extension in the context of Kotlin? Explain.

In Kotlin, we can add or delete method functionality using extensions, even without inheriting or altering them. Extensions are statistically resolved. It provides a callable function that may be invoked with a dot operation, rather than altering the existing class.


Function Extension
 – Kotlin allows users to specify a method outside of the main class via function extension. We’ll see how the extension is implemented at the functional level in the following example:

______________________

// KOTLIN
class Sample {
 var str : String = "null"
   
 fun printStr() {
     print(str)
 }        
}
fun main(args: Array<String>) {
 var  a = Sample()
 a.str = "Interview"
 var  b = Sample()
 b.str = "Bit"
 var  c = Sample()
 c.str = a.add(b)
 c.printStr()
}
// function extension
fun Sample.add(a : Sample):String{
 var temp = Sample()
 temp.str = this.str + " " +a.str
 return temp.str
}
________________________

Output:-

___________________

Interview Bit
______________

Explanation:-

We don’t have a method named “addStr” inside the “Sample” class in the preceding example, but we are implementing the same method outside of the class. This is all because of function extension.

Give me name of the extension methods Kotlin provides to java.io.File?

  • bufferedReader(): Use for reading contents of a file into BufferedReader
  • readBytes() : Use for reading contents of file to ByteArray
  • readText(): Use of reading contents of file to a single String
  • forEachLine() : Use for reading a file line by line in Kotlin
  • readLines(): Use to reading lines in file to List


Others:

What is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE? ☆☆☆

Details: Explain what is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE?

fun printHello(name : String?) : Unit { 
   if (name != null) 
     print("Hello, $name!") 
   else 
     print("Hi there!") 
   // We don't need to write 'return Unit.VALUE' or 'return', although we could 
}

Answer: The purpose is the same as C's or Java's void. Only Unit is a proper type, so it can be passed as a generic argument etc.

  1. Why we don't call it "Void": because the word "void" means "nothing", and there's another type, Nothing, that means just "no value at all", i.e. the computation did not complete normally (looped forever or threw an exception). We could not afford the clash of meanings.

  2. Why Unit has a value (i.e. is not the same as Nothing): because generic code can work smoothly then. If you pass Unit for a generic parameter T, the code written for any T will expect an object, and there must be an object, the sole value of Unit.

  3. How to access that value of Unit: since it's a singleton object, just say Unit

  4. UNIT actually contains valuable information, it basically just means "DONE". It just returns the information to the caller, that the method has been finished.

Source: stackoverflow.com


Aaa

Comments

Popular posts from this blog

Jetpack Compose based Android interview and questions

Null safety based Kotlin interview questions and answers

CustomView based Android interview questions and answers