Standard Functions in Kotlin

Kotlin provides a standard library to augment the features of the Java standard library, I hope you remember that we can use the kotlin to call Java, or java works inside kotlin programs.

Few of Kotlin Standard Functions are below:

  • Higher Order functions implementing idiomatic process
  • Extensions function provides query Operations such as eager and lazy, eager is useful in collections and lazy is useful in sequences
  • Utilities for working with chars and strings
  • Extension for JDK classes to handle IO processes and threading
  • Few standard library packages are : kotlin.annotations, kotlin.kotlin.collections, kotlin.browser, kotlin.system

Below are few helpful Kotlin Standard Library Functions:

  • Apply
  • let
  • with
  • run

Apply

I have been trying to write about apply but I am not able to understand or I didn't find the good definition in simple terms, So I would try to write something simple but I am no expert on it.

What if Apply in kotlin ?
Apply is one of the functions in Kotlin Standard library, apply function is used to call functions on the object and return the object with modification, and these modifications are done by the functions we call.

apply will help the user to call functions but apply will not affect the object. The functions we call inside the apply will modify the object and returns the modified object.

There are scenarios, where functions return something like Int, Float, String..., but there are cases whether a function will return the object reference.

The latter part, when functions return the object, the functions will perform some operations then only it returns the object, not when you invoke something after the functions call you may receive different values.

Similar to the above functions, the apply helps to return the object reference even when the function's return type is not Object.

I do understand that we can call the functions using the object instead of apply function. So, as like you Even I don't know much of use cases for apply functions in kotlin

One of the advantages is when you want to call more functions from the same object continuously then apply will reduce the number lines of code.

Apply function is extension function declared on Any, and every Class/object is sub-class to Any class, So you could use apply function on every object Kotlin.

fun main(args:Array<String>)
{
    var exp = ExampleForApply()
    exp.apply {
            justPrint("hello")
            i=200
        }.printIvalue()
}
class ExampleForApply{
    var I =100;
    fun justPrint(tobePrinted:String){
        println("I am here to print : $tobePrinted")
    }
    fun printIvalue(){
        println("The I value is  : $i")
    }
}

the above output can be achieved without using apply as well, like below kotlin sample program

fun main(args:Array<String>)
{
    var exp = ExampleForApply()
    exp.justPrint("hello")
	// change I value to 200
	exp.i = 200
	exp.printIvalue()
}
class ExampleForApply{
    var I =100;
    fun justPrint(tobePrinted:String){
        println("I am here to print : $tobePrinted")
    }
    fun printIvalue(){
        println("The I value is  : $i")
    }
}

Above program achieve the same thing, one of the advantages of using apply is when you want to call more number of function or variable sequentially from the same object then you could use apply function

let Standard function in kotlin

let Standard function in kotlin


Let me waste your time by telling recap of Nullable :
A function which accept not-nullable parameter will not accept the nullable types in normal times, but when user checks the for Nullability and if the value is not null then only inside the block of not-null check you can pass this nullable values to a functions which accepts non-nullable.

fun main(args:Array<String>)
{
    var str:String? = "I have never watched star-wars"
    if(str != null){
        lengthOfStringNormalMethod(str)
    }else{
        println("It is a null value")
    }
}
// using if block t check null
fun lengthOfStringNormalMethod(str:String){
    // calling function
    println(str.toUpperCase())
    // below is calling variable
    println(str.length)
}

You cannot call any function using the nullable type object, even when the value is not null. In below example, I am trying to call a variable and function on the nullable type variable 'str'

You may face Below error : Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
fun main(args:Array<String>)
{
    var str:String? = "I have never watched star-wars"
    // calling function
    println(str.toUpperCase())
    // below is calling variable
    println(str.length)
}

What is let standard function :

kotlin let function helps to perform the operations on the nullable types just like non-nullable types

For example, you can call the function on a nullable object using let function, or you pass the nullable argument to a function which accepts non-nullable types without checking for the null by using let standard function.

let standard function is also an extension function for the Any datatype class, so you can use let with the class you wish to use.

In the below kotlin example program, we are passing a nullable data type to function which accepts non-nullable parameters and also we are calling a function on the nullable type variable.

fun main(args:Array<String>){
 var str:String? = "chercher tech"
	// calling a function on nullable type variable
    str?.toUpperCase()
	// passing the nullable type argument to a function
	// which accept only non-nullable
    str?.let { justPrint(str) }
}
// function accept non-nullable string
fun justPrint(tobePrinted:String){
    println("I am here to print : $tobePrinted")
}

let and safe call Operator :

In the above example, you might see that I have used an operator before the let function just like a safe call operator. indeed, it is the safe call operator

Safe call operator calls the method / property only if the given object is not null, if the object is null then safe call operator will not give a call to the method or variable(property).

so when the value is null it, kotlin compiler will not execute the let block, for example, take the str value as null, there will be no output if you execute it as safe call operator avoids the let in case the value is null.

fun main(args:Array<String>)
{
	var str:String? = null
	// caling a function on nullable type variable
    str?.toUpperCase()
	// passing the nullable type argument to a function
	// which accept only non-nullable
    str?.let { justPrint(str) }
}
// function accept non-nullable string
fun justPrint(tobePrinted:String){
    println("I am here to print : $tobePrinted")
}

let as Block code :

You can use the let function to create a block code, Inside the block code you can write the functions and variable, these are limited inside the let only you cannot access them outside of that let.

fun main(args:Array<String>)
{
    var str = "kotlin"
    str.let {
        var letVariable = 10
        fun SomeFunctonInsideLet(){
            println("You talkin' to ME ?")
        }
        // calling a function
        SomeFunctonInsideLet()
        println("letVariable value is : $letVariable")
        // printing
        println(str)
        // convert string to UPPER case
        println(str.toUpperCase())
    }
}

I would like you to edit the above main block and make a call to SomeFunctonInsideLet() and check whether call passes or fails

You can have nested let blocks, I mean let block inside a let block.

Return value using let standard function :

The last value without assignment inside the let block will be considered as the return value of the let block. In the below code, the return value is Int.

With function in kotlin

with standard library function in kotlin allows you to call multiple properties(variables) and functions on the same object without repeatedly using the function

In simple terms, use any class Constructor (object) with with function will go into the air, so it will be present inside the block and we can use the methods inside the object without any object reference afterward.

fun main(args:Array<String>)
{
    fun sampleFunction() = with(ExampleClass()){
        justPrint("hello")
        printValue()
    }
}
class ExampleClass{
    var I =100;
    fun justPrint(tobePrinted:String){
        println("I am here to print : $tobePrinted")
    }
    fun printValue(){
        println("The I value is  : $i")
    }
}

You can use the with function as block without depending on function like above.

fun main(args:Array<String>)
{
    with(ExampleClass()) {
        justPrint("hello")
        printValue()
    }
}
class ExampleClass{
    var I =100;
    fun justPrint(tobePrinted:String){
        println("I am here to print : $tobePrinted")
    }
    fun printValue(){
        println("The I value is  : $i")
    }
}

run function in kotlin

run is also similar to the with and let, it helps to define a block of code.

fun main(args:Array<String>)
{
    var xyz = run {
        println("ths example for run")
        // below is the last value without assignment
        3*3
    }
    println(xyz)
}

You can use the run function on object

fun main(args:Array<String>)
{
    ExampleClass().run {
        println("really I do not know the use of run")
    }
}
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions