Kotlin – Destructuring Declarations ”; Previous Next Kotlin contains many features of other programming languages. It allows you to declare multiple variables at once. This technique is called Destructuring declaration. Following is the basic syntax of the destructuring declaration. val (name, age) = person In the above syntax, we have created an object and defined all of them together in a single statement. Later, we can use them as follows. println(name) println(age) Now, let us see how we can use the same in our real-life application. Consider the following example where we are creating one Student class with some attributes and later we will be using them to print the object values. Live Demo fun main(args: Array<String>) { val s = Student(“TutorialsPoint.com”,”Kotlin”) val (name,subject) = s println(“You are learning “+subject+” from “+name) } data class Student( val a :String,val b: String ){ var name:String = a var subject:String = b } The above piece of code will yield the following output in the browser. You are learning Kotlin from TutorialsPoint.com Print Page Previous Next Advertisements ”;
Category: kotlin
Kotlin – Visibility Control
Kotlin – Visibility Control (Modifiers) ”; Previous Next The Kotlin visibility modifiers are the keywords that set the visibility of classes, objects, interface, constructors, functions as well as properties and their setters. Though getters always have the same visibility as their properties, so we can not set their visibility. Setters are the functions which are used to set the values of the properties, where as getters are the functions which are used to get the values of those properties. There are four visibility modifiers in Kotlin: public private protected internal The default visibility is public. These modifiers can be used at multiple places such as class header or method body. Let”s look into the detail of these modifiers: Public Modifier Public modifier is accessible from anywhere in the project workspace. If no access modifier is specified, then by default it will be in the public scope. In all our previous examples, we have not mentioned any modifier, hence, all of them are in the public scope. Following is an example to understand more on how to declare a public variable or method. class publicExample { val i = 1 fun doSomething() { } } In the above example, we have not mentioned any modifier, so the method and variable defined here, are by default public. Though above example can be written with public modifier explicitly as follows: public class publicExample { public val i = 1 public fun doSomething() { } } Private Modifier The classes, methods, packages and other properties can be declared with a private modifier. This modifier has almost the exact opposite meaning of public which means a private member can not be accessed outside of its scope. Once anything is declared as private, then it can be accessible within its immediate scope only. For instance, a private package can be accessible within that specific file. A private class or interface can be accessible only by its data members, etc. private class privateExample { private val i = 1 private val doSomething() { } } In the above example, the class privateExample is only accessible from within the same source file and the variable i and method doSomething can only be accessed from inside of class privateExample. Example Let”s check a simple example showing the usage of private members: open class A() { private val i = 1 fun doSomething(){ println(“Inside doSomething” ) println(“Value of i is $i” ) } } class B : A() { fun printValue(){ doSomething() // println(“Value of i is $i” ) } } fun main(args: Array<String>) { val a = A() val b = B() b.printValue() } When you run the above Kotlin program, it will generate the following output: Inside doSomething Value of i is 1 Here we can not access variable i inside class B because it has been defined as private which means it can be accessed inside the class itself and no where else. Protected Modifier Protected is another access modifier for Kotlin, which is currently not available for top level declaration like any package cannot be protected. A protected class or interface or properties or function is visible to the class itself and it”s subclasses only. package one; class A() { protected val i = 1 } class B : A() { fun getValue() : Int { return i } } In the above example, the variable i is declared as protected, hence, it is only visible to class itself and it”s subclasses. Example Let”s check a simple example showing the usage of protected members: open class A() { protected val i = 1 protected fun doSomething(){ println(“Inside doSomething” ) println(“Value of i is $i” ) } } class B : A() { fun printValue(){ doSomething() println(“Value of i is $i” ) } } fun main(args: Array<String>) { val a = A() val b = B() //a.doSomething() b.printValue() } When you run the above Kotlin program, it will generate the following output: Inside doSomething Value of i is 1 Value of i is 1 Here we can not call doSomething() even using an object of class A because it has been defined as protected which means it can be accessed inside the class itself or in its subclasses only. Internal Modifier Internal is a newly added modifier in Kotlin. If anything is marked as internal, then the specific field will marked as the internal field. An Internal package is visible only inside the module under which it is implemented. An internal class interface is visible only by other class present inside the same package or the module. In the following example, we will see how to implement an internal method. package one internal class InternalExample { } class publicExample{ internal val i = 1 internal fun doSomething() { } } In the above example, class InternalExample is only accessible from inside the same module, similarly variable i and function doSomething() are also accessible from inside the same module only, even though the class publicExample can be accessed from anywhere because this class has public visibility by default. Example Let”s check a simple example showing the usage of internal members: package com.tutorialspoint.modifiers open class A() { internal val i = 1 internal fun doSomething(){ println(“Inside doSomething” ) println(“Value of i is $i” ) } } class B : A() { fun printValue(){ doSomething() println(“Value of i is $i” ) } } fun main(args: Array<String>) { val a = A() val b = B() a.doSomething() b.printValue() } When you run the above Kotlin program, it will generate the following output: Inside doSomething Value of i is 1 Inside doSomething Value of i is 1 Value of i is 1 Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which one is not a visibility modifier in Kotlin : A – public B – private C – abstract D – internal Answer : C Explanation Abstract is not a visibility modifier in Kotlin, though it is used to define an abstract class. Show Answer
Kotlin – Delegation
Kotlin – Delegation ”; Previous Next Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object. The following example demonstrates how this happens in Kotlin. Live Demo interface Base { fun printMe() //abstract method } class BaseImpl(val x: Int) : Base { override fun printMe() { println(x) } //implementation of the method } class Derived(b: Base) : Base by b // delegating the public method on the object b fun main(args: Array<String>) { val b = BaseImpl(10) Derived(b).printMe() // prints 10 :: accessing the printMe() method } In the example, we have one interface “Base” with its abstract method named “printme()”. In the BaseImpl class, we are implementing this “printme()” and later from another class we are using this implementation using “by” keyword. The above piece of code will yield the following output in the browser. 10 Property Delegation In the previous section, we have learned about the delegation design pattern using “by” keyword. In this section, we will learn about delegation of properties using some standard methods mentioned in Kotlin library. Delegation means passing the responsibility to another class or method. When a property is already declared in some places, then we should reuse the same code to initialize them. In the following examples, we will use some standard delegation methodology provided by Kotlin and some standard library function while implementing delegation in our examples. Using Lazy() Lazy is a lambda function which takes a property as an input and in return gives an instance of Lazy<T>, where <T> is basically the type of the properties it is using. Let us take a look at the following to understand how it works. Live Demo val myVar: String by lazy { “Hello” } fun main(args: Array<String>) { println(myVar +” My dear friend”) } In the above piece of code, we are passing a variable “myVar” to the Lazy function, which in return assigns the value to its object and returns the same to the main function. Following is the output in the browser. Hello My dear friend Delegetion.Observable() Observable() takes two arguments to initialize the object and returns the same to the called function. In the following example, we will see how to use Observable() method in order to implement delegation. Live Demo import kotlin.properties.Delegates class User { var name: String by Delegates.observable(“Welcome to Tutorialspoint.com”) { prop, old, new -> println(“$old -> $new”) } } fun main(args: Array<String>) { val user = User() user.name = “first” user.name = “second” } The above piece of code will yield the following output in the browser. first -> second In general, the syntax is the expression after the “by” keyword is delegated. The get() and set() methods of the variable p will be delegated to its getValue() and setValue() methods defined in the Delegate class. class Example { var p: String by Delegate() } For the above piece of code, following is the delegate class that we need to generate in order to assign the value in the variable p. class Delegate { operator fun getValue(thisRef: Any?, property: KProperty<*>): String { return “$thisRef, thank you for delegating ”${property.name}” to me!” } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { println(“$value has been assigned to ”${property.name} in $thisRef.””) } } While reading, getValue() method will be called and while setting the variable setValue() method will be called. Print Page Previous Next Advertisements ”;
Kotlin – Extension
Kotlin – Extensions ”; Previous Next Kotlin extensions provide the ability to extend a class with new functionality without implementing the inheritance concept by a class or using design pattern such as Decorator. These extensions basically add some functionality in an existing class without extending the class. The Kotlin extension allows to write new functions for a class from a third-party library without modifying the class. The beauty of the extension functions is that they can be called in the usual way, as if they were methods of the original class and these new functions are called Extension Functions. Similarly, we can also define extension properties for an existing Kotlin class. Extension Function A kotlin extension function is a member function of a class, which is defined outside the class. The created extension functions are used as a regular function inside that class. Syntax Following is the syntax to define an extension function. Here, the extension function is declared with using the class name and also with using method name. fun <class_name>.<method_name>(){ …. function body } Example In function extension, Kotlin allows to define a method outside of the main class. In the following example, we will see how the extension is implemented at the functional level. class Alien { var skills : String = “null” fun printMySkills() { print(skills) } } fun main(args: Array<String>) { var a1 = Alien() a1.skills = “JAVA” //a1.printMySkills() var a2 = Alien() a2.skills = “SQL” //a2.printMySkills() var a3 = Alien() a3.skills = a1.addMySkills(a2) a3.printMySkills() } fun Alien.addMySkills(a:Alien):String{ var a4 = Alien() a4.skills = this.skills + ” ” +a.skills return a4.skills } In the above example, we don’t have any method inside “Alien” class named as “addMySkills()”, however, we still are implementing the same method somewhere else outside of the class, This is the magic of extension. When you run the above Kotlin program, it will generate the following output: JAVA SQL Extended Library Classes Kotlin allows to extend the standard library classes as well as user-defined classes. For example, if you need a specialised function for standard Kotlin String class which will return the number of vowels available in the string, such method is not already available in String class but you can use an extension function to accomplish this task. fun main(args: Array<String>) { val str = “Good morning Kotlin” val result = str.countVowels() println(“Number of vowels: $result”) } fun String.countVowels(): Int{ var vowels = 0 for (i in 0.. this.length – 1) { val ch = this[i] if (ch == ”a” || ch == ”e” || ch == ”i” || ch == ”o” || ch == ”u”) { ++vowels } } return vowels; } When you run the above Kotlin program, it will generate the following output: Number of vowels: 6 Companion Object Extensions Kotlin provides another mechanism to implement static functionality of Java. This can be achieved using the companion object which is declared inside a class and marked with the companion keyword. Using this mechanism, we can create an object of a class inside a factory method and later we can just call that method using the reference of the class name. In the following example, we will create a “companion object”. fun main(args: Array<String>) { println(“Heyyy!!!”+A.show()) } class A { companion object { fun show():String { return(“You are learning Kotlin from TutorialsPoint.com”) } } } When you run the above Kotlin program, it will generate the following output: Heyyy!!! You are learning Kotlin from TutorialsPoint.com The above example seems like static in Java, however, in real-time we are creating an object as a member variable of that same class. This is why it is also included under extension property and can be alternatively called as an object extension. You are basically extending the object of the same class to use some of the member functions. Extension with Nullable Receiver Kotlin allows to define Extension Functions with a nullable class type. These extension function can be called on a nullable object variable. To define an extension for Nullable receiver, we just need to add a check for null receiver inside the extension function, and the appropriate value is returned. fun main(args: Array<String>) { var str1 = “Good morning Kotlin” var str2 : String? = null var result = str1.countVowels() println(“Number of vowels in str1 : $result”) result = str2.countVowels() println(“Number of vowels in str2 : $result”) } fun String?.countVowels(): Any{ if (this == null) return “null” var vowels = 0 for (i in 0.. this.length – 1) { val ch = this[i] if (ch == ”a” || ch == ”e” || ch == ”i” || ch == ”o” || ch == ”u”) { ++vowels } } return vowels; } When you run the above Kotlin program, it will generate the following output: Number of vowels in str1 : 6 Number of vowels in str2 : null Extension Properties Kotlin allows to define extension properties in very similar way like we defined extension function. Extension properties are also defined outside of the class. Since extensions do not actually insert members into classes, there is no efficient way for an extension property to have a backing field. This is why initializers are not allowed for extension properties. We can add getter and setter along with the property which are nothing but the extension functions. class Temperature(var celsius: Float) fun main(args: Array<String>) { val t = Temperature(40f) println(t.fahrenheit) t.fahrenheit = 85f println(t.celsius) } var Temperature.fahrenheit: Float get() = (celsius * 9 / 5) + 32 set(value) { celsius = (value – 32) * 5 / 9 } When you run the above Kotlin program, it will generate the following output: 104.0 29.444445 Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which one is true about kotlin extension function : A – They are defined outside the class without impacting existing functionality B – We can inherit Kotlin class and add a new function inside the class C – Latest version of Kotlin does not allow to
Kotlin – Data Classes
Kotlin – Data Classes ”; Previous Next In this chapter, we will learn about Kotlin Data Classes. A Kotlin Data Class is used to hold the data only and it does not provide any other functionality apart from holding data. There are following conditions for a Kotlin class to be defined as a Data Class: The primary constructor needs to have at least one parameter. All primary constructor parameters need to be marked as val or var. Data classes cannot be abstract, open, sealed, or inner. The class may extend other classes or implement interfaces. If you are using Kotlin version before 1.1, the class can only implement interfaces. Syntax It”s simple to define a Kotlin Data Class. If a Kotlin class is marked with data keyword then it becomes a data class. For example: data class Book(val name: String, val publisher: String, var reviewScore: Int) Good thing about Kotlin Data Class is that when you declare a Kotlin Data Class, the compiler generates Constructor, toString(), equals(), hashCode(), and additional copy() and componentN() functions automatically. Example A Kotlin Data Class is instantiated the same way as other Kotlin classes: data class Book(val name: String, val publisher: String, var reviewScore: Int) fun main(args: Array<String>) { val book = Book(“Kotlin”, “Tutorials Point”, 10) println(“Name = ${book.name}”) println(“Publisher = ${book.publisher}”) println(“Score = ${book.reviewScore}”) } When you run the above Kotlin program, it will generate the following output: Name = Kotlin Publisher = Tutorials Point Score = 10 Copy Function The copy() function is created automatically when we define a Kotlin Data Class. This copy function can be used to copy an object altering some of its properties but keeping the rest unchanged. Following is an example: data class Book(val name: String, val publisher: String, var reviewScore: Int) fun main(args: Array<String>) { val original = Book(“Kotlin”, “Tutorials Point”, 10) val copied = original.copy(reviewScore=5) println(“Original Book”) println(“Name = ${original.name}”) println(“Publisher = ${original.publisher}”) println(“Score = ${original.reviewScore}”) println(“Copied Book”) println(“Name = ${copied.name}”) println(“Publisher = ${copied.publisher}”) println(“Score = ${copied.reviewScore}”) } When you run the above Kotlin program, it will generate the following output: Original Book Name = Kotlin Publisher = Tutorials Point Score = 10 Copied Book Name = Kotlin Publisher = Tutorials Point Score = 5 toString Function The toString() function is also created automatically when we define a Kotlin Data Class. This function returns a string representation of the object. Following is an example: data class Book(val name: String, val publisher: String, var reviewScore: Int) fun main(args: Array<String>) { val book = Book(“Kotlin”, “Tutorials Point”, 10) println(book.toString()) } When you run the above Kotlin program, it will generate the following output: Book(name=Kotlin, publisher=Tutorials Point, reviewScore=10) hashCode() and equals() Functions The hasCode()function returns hash code for the object. If two objects are equal, hashCode() returns the same integer value for the objects. The equals() function returns true if two objects are equal or they have same hasCode value otherwise it returns false. Following is an example: data class Book(val name: String, val publisher: String, var reviewScore: Int) fun main(args: Array<String>) { val original = Book(“Kotlin”, “Tutorials Point”, 10) val copy1 = original.copy(reviewScore=5) val copy2 = original.copy(reviewScore=7) println(“Original Hashcode = ${original.hashCode()}”) println(“Copy1 Hashcode = ${copy1.hashCode()}”) println(“Copy2 Hashcode = ${copy2.hashCode()}”) if( copy1.equals(copy2)){ println(“Copy1 is equal to Copy2.”) }else{ println(“Copy1 is not equal to Copy2.”) } } When you run the above Kotlin program, it will generate the following output: Original Hashcode = 1957710662 Copy1 Hashcode = 1957710657 Copy2 Hashcode = 1957710659 Copy1 is not equal to Copy2. Destructuring Declarations We can destructure an object into a number of variables using destructing declaration. For example: data class Book(val name: String, val publisher: String, var reviewScore: Int) fun main(args: Array<String>) { val book = Book(“Kotlin”, “Tutorials Point”, 10) val( name, publisher,reviewScore ) = book println(“Name = $name”) println(“Publisher = $publisher”) println(“Score = $reviewScore”) } When you run the above Kotlin program, it will generate the following output: Name = Kotlin Publisher = Tutorials Point Score = 10 Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – What is the purpose of Data Classes in Kotlin : A – Kotlin Data Classes are defined to hold the data only. B – Kotlin Data Classes are synonym of abstract classes C – Kotlin Data Classes are defined to hold data and associated functions D – All are incorrect about data classes Answer : A Explanation Kotlin Data Classes are defined to hold the data only. Show Answer Q 2 – Which function is not created by default when we define a Kotlin Data Class A – copy() function B – toString() function C – componentN() D – All the above Answer : D Explanation All the mentioned functions are created automatically when we define Kotlin Data Class. Show Answer Q 2 – What is the function of componentN() in Kotlin Data Class A – It is used to define new property of the class B – It is used to count the number of properties in the class C – It is used to destructure an object into a number of variables D – All the above Answer : C Explanation The function componentN() is used to destructure an object into a number of variables. Print Page Previous Next Advertisements ”;
Kotlin – Arrays
Kotlin – Arrays ”; Previous Next Arrays are used to store multiple items of the same data-type in a single variable, such as an integer or string under a single variable name. For example, if we need to store names of 1000 employees, then instead of creating 1000 different string variables, we can simply define an array of string whose capacity will be 1000. Like any other modern programming languages, Kotlin also supports arrays and provide a wide range of array properties and support functions to manipulate arrays. Creating Arrays in Kotlin To create an array in Kotlin, we use the arrayOf() function, and place the values in a comma-separated list inside it: val fruits = arrayOf(“Apple”, “Mango”, “Banana”, “Orange”) Optionally we can provide a data type as follows: val fruits = arrayOf<String>(“Apple”, “Mango”, “Banana”, “Orange”) Alternatively, the arrayOfNulls() function can be used to create an array of a given size filled with null elements. Primitive type Arrays Kotlin also has some built-in factory methods to create arrays of primitive data types. For example, the factory method to create an integer array is: val num = intArrayOf(1, 2, 3, 4) Other factory methods available for creating arrays: byteArrayOf() charArrayOf() shortArrayOf() longArrayOf() Get and Set the Elements of an Array We can access an array element by using the index number inside square brackets. Kotlin array index starts with zero (0). So if you want to access 4th element of the array then you will need to give 3 as the index. Example fun main(args: Array<String>) { val fruits = arrayOf<String>(“Apple”, “Mango”, “Banana”, “Orange”) println( fruits [0]) println( fruits [3]) } When you run the above Kotlin program, it will generate the following output: Apple Orange Kotlin also provides get() and set() member functions to get and set the value at a particular index. Check the following example: Example fun main(args: Array<String>) { val fruits = arrayOf<String>(“Apple”, “Mango”, “Banana”, “Orange”) println( fruits.get(0)) println( fruits.get(3)) // Set the value at 3rd index fruits.set(3, “Guava”) println( fruits.get(3)) } When you run the above Kotlin program, it will generate the following output: Apple Orange Guava Kotlin Array Length Kotlin provides array property called size which returns the size i.e. length of the array. Example fun main(args: Array<String>) { val fruits = arrayOf<String>(“Apple”, “Mango”, “Banana”, “Orange”) println( “Size of fruits array ” + fruits.size ) } When you run the above Kotlin program, it will generate the following output: Size of fruits array 4 We can also use count() member function to get the size of the array. Loop Through an Array We can use for loop to loop through an array. Example fun main(args: Array<String>) { val fruits = arrayOf<String>(“Apple”, “Mango”, “Banana”, “Orange”) for( item in fruits ){ println( item ) } } When you run the above Kotlin program, it will generate the following output: Apple Mango Banana Orange Check if an Element Exists We can use the in operator alongwith if…else to check if an element exists in an array. Example fun main(args: Array<String>) { val fruits = arrayOf<String>(“Apple”, “Mango”, “Banana”, “Orange”) if (“Mango” in fruits){ println( “Mango exists in fruits” ) }else{ println( “Mango does not exist in fruits” ) } } When you run the above Kotlin program, it will generate the following output: Mango exists in fruits Distinct Values from Array Kotlin allows to store duplicate values in an array, but same time you can get a set of distinct values stored in the array using distinct() member function. Example fun main(args: Array<String>) { val fruits = arrayOf<String>(“Apple”, “Mango”, “Banana”, “Orange”, “Apple”) val distinct = fruits.distinct() for( item in distinct ){ println( item ) } } When you run the above Kotlin program, it will generate the following output: Apple Mango Banana Orange Dropping Elements from Array We can use drop() or dropLast() member functions to drop elements from the beginning or from the last respectively. Example fun main(args: Array<String>) { val fruits = arrayOf<String>(“Apple”, “Mango”, “Banana”, “Orange”, “Apple”) val result = fruits.drop(2) // drops first two elements. for( item in result ){ println( item ) } } When you run the above Kotlin program, it will generate the following output: Banana Orange Apple Checking an Empty Array We can use isEmpty() member function to check if an array is empty or not. This function returns true if the array is empty. Example fun main(args: Array<String>) { val fruits = arrayOf<String>() println( “Array is empty : ” + fruits.isEmpty()) } When you run the above Kotlin program, it will generate the following output: “Array is empty : true Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which of the following is true about Kotlin Arrays? A – Kotlin arrays are capable to store all data types. B – Kotlin arrays can be created using either arrayOf() or arrayOfNulls() functions. C – Kotlin provides a rich set of properties and functions to manipulate arrays. D – All of the above Answer : D Explanation All the mentioned statements are correct about Kotlin Arrays. Show Answer Q 2 – What will be the output of the following code segment? fun main(args: Array<String>) { val fruits = arrayOf<String>(“Apple”, “Mango”, “Banana”, “Orange”) println( fruits [2]) } A – Apple B – Mango C – Banana D – None of the above Answer : C Explanation Kotlin index starts from 0, so at 2 index we will find 3rd element which is Banana. Show Answer Q 3 – How to get the size of a Kotlin array? A – Using length() function B – Using size property C – Using count() function D – B and C both Answer : D Explanation Option D is correct because we can get the size of an array using either size property or count() function. Print Page Previous Next Advertisements ”;
Kotlin – Functions
Kotlin – Functions ”; Previous Next Kotlin is a statically typed language, hence, functions play a great role in it. We are pretty familiar with function, as we are using function throughout our examples in our last chapters. A function is a block of code which is written to perform a particular task. Functions are supported by all the modern programming languages and they are also known as methods or subroutines. At a broad level, a function takes some input which is called parameters, perform certain actions on these inputs and finally returns a value. Kotlin Built-in Functions Kotlin provides a number of built-in functions, we have used a number of buil-in functions in our examples. For example print() and println() are the most commonly used built-in function which we use to print an output to the screen. Example fun main(args: Array<String>) { println(“Hello, World!”) } User-Defined Functions Kotlin allows us to create our own function using the keyword fun. A user defined function takes one or more parameters, perform an action and return the result of that action as a value. Syntax fun functionName(){ // body of function } Once we defined a function, we can call it any number of times whenever it is needed. Following isa simple syntax to call a Kotlin function: functionName() Example Following is an example to define and call a user-defined function which will print simple “Hello, World!”: fun main(args: Array<String>) { printHello() } fun printHello(){ println(“Hello, World!”) } When you run the above Kotlin program, it will generate the following output: Hello, World! Function Parameters A user-defined function can take zero or more parameters. Parameters are options and can be used based on requirement. For example, our above defined function did not make use of any paramenter. Example Following is an example to write a user-defined function which will add two given numbers and print their sum: fun main(args: Array<String>) { val a = 10 val b = 20 printSum(a, b) } fun printSum(a:Int, b:Int){ println(a + b) } When you run the above Kotlin program, it will generate the following output: 30 Return Values A kotlin function return a value based on requirement. Again it is very much optional to return a value. To return a value, use the return keyword, and specify the return type after the function”s parantheses Example Following is an example to write a user-defined function which will add two given numbers and return the sum: fun main(args: Array<String>) { val a = 10 val b = 20 val result = sumTwo(a, b) println( result ) } fun sumTwo(a:Int, b:Int):Int{ val x = a + b return x } When you run the above Kotlin program, it will generate the following output: 30 Unit-returning Functions If a function does not return a useful value, its return type is Unit. Unit is a type with only one value which is Unit. fun sumTwo(a:Int, b:Int):Unit{ val x = a + b println( x ) } The Unit return type declaration is also optional. The above code is equivalent to: fun sumTwo(a:Int, b:Int){ val x = a + b println( x ) } Kotlin Recursive Function Recursion functions are useful in many scenerios like calculating factorial of a number or generating fibonacci series. Kotlin supports recursion which means a Kotlin function can call itself. Syntax fun functionName(){ … functionName() … } Example Following is a Kotlin program to calculate the factorial of number 10: fun main(args: Array<String>) { val a = 4 val result = factorial(a) println( result ) } fun factorial(a:Int):Int{ val result:Int if( a <= 1){ result = a }else{ result = a*factorial(a-1) } return result } When you run the above Kotlin program, it will generate the following output: 24 Kotlin Tail Recursion A recursive function is eligible for tail recursion if the function call to itself is the last operation it performs. Example Following is a Kotlin program to calculate the factorial of number 10 using tail recursion. Here we need to ensure that the multiplication is done before the recursive call, not after. fun main(args: Array<String>) { val a = 4 val result = factorial(a) println( result ) } fun factorial(a: Int, accum: Int = 1): Int { val result = a * accum return if (a <= 1) { result } else { factorial(a – 1, result) } } When you run the above Kotlin program, it will generate the following output: 24 Kotlin tail recursion is useful while calculating factorial or some other processing on large numbers. So to avoide java.lang.StackOverflowError, you must use tail recursion. Higher-Order Functions A higher-order function is a function that takes another function as parameter and/or returns a function. Example Following is a function which takes two integer parameters, a and b and additionally, it takes another function operation as a parameter: fun main(args: Array<String>) { val result = calculate(4, 5, ::sum) println( result ) } fun sum(a: Int, b: Int) = a + b fun calculate(a: Int, b: Int, operation:(Int, Int) -> Int): Int { return operation(a, b) } When you run the above Kotlin program, it will generate the following output: 9 Here we are calling the higher-order function passing in two integer values and the function argument ::sum. Here :: is the notation that references a function by name in Kotlin. Example Let”s look one more example where a function returns another function. Here we defined a higher-order function that returns a function. Here (Int) -> Int represents the parameters and return type of the square function. fun main(args: Array<String>) { val func = operation() println( func(4) ) } fun square(x: Int) = x * x fun operation(): (Int) -> Int { return ::square } When you run the above Kotlin program, it will generate the following output: 9 Kotlin Lambda Function Kotlin lambda is a function which has no name and defined with a curly braces {} which takes zero or more parameters and body of function. The body of
Kotlin – Operators
Kotlin – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Kotlin is rich in built-in operators and provide the following types of operators: Arithmetic Operators Relational Operators Assignment Operators Unary Operators Logical Operators Bitwise Operations Now let”s look into these Kotlin Operators one by one. (a) Kotlin Arithmetic Operators Kotlin arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication and division etc. Operator Name Description Example + Addition Adds together two values x + y – Subtraction Subtracts one value from another x – y * Multiplication Multiplies two values x * y / Division Divides one value by another x / y % Modulus Returns the division remainder x % y Example Following example shows different calculations using Kotlin Arithmetic Operators: fun main(args: Array<String>) { val x: Int = 40 val y: Int = 20 println(“x + y = ” + (x + y)) println(“x – y = ” + (x – y)) println(“x / y = ” + (x / y)) println(“x * y = ” + (x * y)) println(“x % y = ” + (x % y)) } When you run the above Kotlin program, it will generate the following output: x + y = 60 x – y = 20 x / y = 2 x * y = 800 x % y = 0 (b) Kotlin Relational Operators Kotlin relational (comparison) operators are used to compare two values, and returns a Boolean value: either true or false. Operator Name Example > greater than x > y < less than x < y >= greater than or equal to x >= y <= less than or equal to x <= y == is equal to x == y != not equal to x != y Example Following example shows different calculations using Kotlin Relational Operators: fun main(args: Array<String>) { val x: Int = 40 val y: Int = 20 println(“x > y = ” + (x > y)) println(“x < y = ” + (x < y)) println(“x >= y = ” + (x >= y)) println(“x <= y = ” + (x <= y)) println(“x == y = ” + (x == y)) println(“x != y = ” + (x != y)) } When you run the above Kotlin program, it will generate the following output: x > y = true x < y = false x >= y = true x <= y = false x == y = false x != y = true (c) Kotlin Assignment Operators Kotlin assignment operators are used to assign values to variables. Following is an example where we used assignment operator = to assign a values into two variables: fun main(args: Array<String>) { val x: Int = 40 val y: Int = 20 println(“x = ” + x) println(“y = ” + y) } When you run the above Kotlin program, it will generate the following output: x = 40 y = 20 Following is one more example where we used assignment operator += to add the value of self variable and assign it back into the same variable: fun main(args: Array<String>) { var x: Int = 40 x += 10 println(“x = ” + x) } When you run the above Kotlin program, it will generate the following output: x = 50 Following is a list of all assignment operators: Operator Example Expanded Form = x = 10 x = 10 += x += 10 x = x – 10 -= x -= 10 x = x – 10 *= x *= 10 x = x * 10 /= x /= 10 x = x / 10 %= x %= 10 x = x % 10 Example Following example shows different calculations using Kotlin Assignment Operators: fun main(args: Array<String>) { var x: Int = 40 x += 5 println(“x += 5 = ” + x ) x = 40; x -= 5 println(“x -= 5 = ” + x) x = 40 x *= 5 println(“x *= 5 = ” + x) x = 40 x /= 5 println(“x /= 5 = ” + x) x = 43 x %= 5 println(“x %= 5 = ” + x) } When you run the above Kotlin program, it will generate the following output: x += 5 = 45 x -= 5 = 35 x *= 5 = 200 x /= 5 = 8 x %= 5 = 3 (d) Kotlin Unary Operators The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean. Following is the list of Kotlin Unary Operators: Operator Name Example + unary plus +x – unary minus -x ++ increment by 1 ++x — decrement by 1 –x ! inverts the value of a boolean !x Example Following example shows different calculations using Kotlin Unary Operators: fun main(args: Array<String>) { var x: Int = 40 var b:Boolean = true println(“+x = ” + (+x)) println(“-x = ” + (-x)) println(“++x = ” + (++x)) println(“–x = ” + (–x)) println(“!b = ” + (!b)) } When you run the above Kotlin program, it will generate the following output: +x = 40 -x = -40 ++x = 41 –x = 40 !b = false Here increment (++) and decrement (–) operators can be used as prefix as ++x or –x as well as suffix as x++ or x–. The only difference between the two forms is that in case we use them as prefix then operator will apply before expression is executed, but if use them as suffix then operator will apply after the expression is executed. (e) Kotlin Logical Operators Kotlin logical operators are used to determine the logic between two variables or values: Following is the list of Kotlin Logical Operators: Operator Name Description Example && Logical and Returns true if both operands
Kotlin – Sets
Kotlin – Sets ”; Previous Next Kotlin set is an unordered collection of items. A Kotlin set can be either mutable (mutableSetOf) or read-only (setOf). Kotlin mutable or immutable sets do not allow to have duplicate elements. Creating Kotlin Sets For set creation, use the standard library functions setOf() for read-only sets and mutableSetOf() for mutable sets. A read-only view of a mutable set can be obtained by casting it to Set. Example fun main() { val theSet = setOf(“one”, “two”, “three”, “four”) println(theSet) val theMutableSet = mutableSetOf(“one”, “two”, “three”, “four”) println(theMutableSet) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four] [one, two, three, four] Loop through Kotlin Sets There are various ways to loop through a Kotlin Set. Lets study them one by one: Using toString() function fun main() { val theSet = setOf(“one”, “two”, “three”, “four”) println(theSet.toString()) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four] Using Iterator fun main() { val theSet = setOf(“one”, “two”, “three”, “four”) val itr = theSet.asIterable().iterator() while (itr.hasNext()) { println(itr.next()) } } When you run the above Kotlin program, it will generate the following output: one two three four Using for loop fun main() { val theSet = setOf(“one”, “two”, “three”, “four”) for (i in theSet.indices) { println(theSet.elementAt(i)) } } When you run the above Kotlin program, it will generate the following output: one two three four Using forEach fun main() { val theSet = setOf(“one”, “two”, “three”, “four”) theSet.forEach { println(it) } } When you run the above Kotlin program, it will generate the following output: one two three four Note – here it works like this operator in Java. Size of Kotlin Set We can use size property to get the total number of elements in a set: fun main() { val theSet = setOf(“one”, “two”, null, “four”, “five”) println(“Size of the Set ” + theSet.size) } When you run the above Kotlin program, it will generate the following output: Size of the Set 5 The “in” Operator The in operator can be used to check the existence of an element in a set. Example fun main() { val theSet = setOf(“one”, “two”, “three”, “four”) if(“two” in theSet){ println(true) }else{ println(false) } } When you run the above Kotlin program, it will generate the following output: true The contain() Method The contain() method can also be used to check the existence of an element in a set. Example fun main() { val theSet = setOf(“one”, “two”, “three”, “four”) if(theSet.contains(“two”)){ println(true) }else{ println(false) } } When you run the above Kotlin program, it will generate the following output: true The isEmpty() Method The isEmpty() method returns true if the collection is empty (contains no elements), false otherwise. Example fun main() { val theSet = setOf(“one”, “two”, “three”, “four”) if(theSet.isEmpty()){ println(true) }else{ println(false) } } When you run the above Kotlin program, it will generate the following output: false The indexOf() Method The indexOf() method returns the index of the first occurrence of the specified element in the set, or -1 if the specified element is not contained in the set. Example fun main() { val theSet = setOf(“one”, “two”, “three”, “four”) println(“Index of ”two” – ” + theSet.indexOf(“two”)) } When you run the above Kotlin program, it will generate the following output: Index of ”two” – 1 The elementAt() Method The elementAt() method can be used to get the element at the specified index in the set. Example fun main() { val theSet = setOf(“one”, “two”, “three”, “four”) println(“Element at 3rd position ” + theSet.elementAt(2)) } When you run the above Kotlin program, it will generate the following output: Element at 3rd position three Set Addition We can use + operator to add two or more sets into a single set. This will add second set into first set, discarding the duplicate elements. Example fun main() { val firstSet = setOf(“one”, “two”, “three”) val secondSet = setOf(“one”, “four”, “five”, “six”) val resultSet = firstSet + secondSet println(resultSet) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four, five, six] Set Subtraction We can use – operator to subtract a set from another set. This operation will remove the common elements from the first set and will return the result. Example fun main() { val firstSet = setOf(“one”, “two”, “three”) val secondSet = setOf(“one”, “five”, “six”) val resultSet = firstSet – secondSet println(resultSet) } When you run the above Kotlin program, it will generate the following output: [two, three] Removing null a Set We can use filterNotNull() method to remove null element from a set. fun main() { val theSet = setOf(“one”, “two”, null, “four”, “five”) val resultSet = theSet.filterNotNull() println(resultSet) } When you run the above Kotlin program, it will generate the following output: [one, two, four, five] Sorting Elements We can use sorted() method to sort the elements in ascending order, or sortedDescending() method to sort the set elements in descending order. fun main() { val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0) var resultSet = theSet.sorted() println(resultSet) resultSet = theSet.sortedDescending() println(resultSet) } When you run the above Kotlin program, it will generate the following output: [-1, 0, 10, 20, 30, 31, 40, 50] [50, 40, 31, 30, 20, 10, 0, -1] Filtering Elements We can use filter() method to filter out the elements matching with the given predicate. fun main() { val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0) val resultSet = theSet.filter{ it > 30} println(resultSet) } When you run the above Kotlin program, it will generate the following output: [31, 40, 50] Dropping First N Elements We can use drop() method to drop first N elements from the set. fun main() { val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0) val resultSet = theSet.drop(3) println(resultSet) } When you run the above Kotlin program, it will generate the following
Kotlin – if…Else Expression
Kotlin – if…else Expression ”; Previous Next Kotlin if…else expressions works like an if…else expression in any other Modern Computer Programming. So let”s start with our traditional if…else statement available in Kotlin. Syntax The syntax of a traditional if…else expression is as follows: if (condition) { // code block A to be executed if condition is true } else { // code block B to be executed if condition is false } Here if statement is executed and the given condition is checked. If this condition is evaluated to true then code block A is executed, otherwise program goes into else part and code block B is executed. Example You can try the following example: fun main(args: Array<String>) { val age:Int = 10 if (age > 18) { print(“Adult”) } else { print(“Minor”) } } When you run the above Kotlin program, it will generate the following output: Minor Kotlin if…else Expression Kotlin if…else can also be used as an expression which returns a value and this value can be assigned to a variable. Below is a simple syntax of Kotlin if…else expression: Syntax val result = if (condition) { // code block A to be executed if condition is true } else { // code block B to be executed if condition is false } If you”re using if as an expression, for example, for returning its value or assigning it to a variable, the else branch is mandatory. Examples fun main(args: Array<String>) { val age:Int = 10 val result = if (age > 18) { “Adult” } else { “Minor” } println(result) } When you run the above Kotlin program, it will generate the following output: Minor You can ommit the curly braces {} when if has only one statement: fun main(args: Array<String>) { val age:Int = 10 val result = if (age > 18) “Adult” else “Minor” println(result) } When you run the above Kotlin program, it will generate the following output: Minor You can include multiple statements in if…else block, in this case the last expression is returned as the value of the block. Try the following example: fun main(args: Array<String>) { val age:Int = 10 val result = if (age > 18) { println(“Given condition is true”) “Adult” } else { println(“Given condition is false”) “Minor” } print(“The value of result : “) println(result) } When you run the above Kotlin program, it will generate the following output: Given condition is false The value of result : Minor Kotlin if…else…if Ladder You can use else if condition to specify a new condition if the first condition is false. Syntax if (condition1) { // code block A to be executed if condition1 is true } else if (condition2) { // code block B to be executed if condition2 is true } else { // code block C to be executed if condition1 and condition2 are false } Example fun main(args: Array<String>) { val age:Int = 13 val result = if (age > 19) { “Adult” } else if ( age > 12 && age < 20 ){ “Teen” } else { “Minor” } print(“The value of result : “) println(result) } When you run the above Kotlin program, it will generate the following output: The value of result : Teen Kotlin Nested if Expression Kotlin allows to put an if expression inside another if expression. This is called nested if expression Syntax if(condition1) { // code block A to be executed if condition1 is true if( (condition2) { // code block B to be executed if condition2 is true }else{ // code block C to be executed if condition2 is fals } } else { // code block D to be executed if condition1 is false } Example fun main(args: Array<String>) { val age:Int = 20 val result = if (age > 12) { if ( age > 12 && age < 20 ){ “Teen” }else{ “Adult” } } else { “Minor” } print(“The value of result : “) println(result) } When you run the above Kotlin program, it will generate the following output: The value of result : Adult Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which of the following is true about Kotlin if expression? A – Kotlin support traditional if…else expression. B – Kotlin if…else expression can be nested. C – Kotlin if…else expression returns a value which can be assigned to a variable. D – All of the above Answer : D Explanation All the mentioned statements are correct about Kotlin if expression. Show Answer Q 2 – Which of the following is not supported by Kotlin? A – if…else if…else B – if…then…else C – if…else… D – None of the above Answer : B Explanation Kotlin does not support if…then…else statement. Show Answer Q 3 – What will be the output of the following code? fun main(args: Array<String>) { var x = 20 var y = 15 var z = “Mango” val result = if (x > y ) { z = “Orange” } else { z = “Apple” } println(“Value of result = $z”) } A – Mango B – Orange C – Apple D – None of the above Answer : B Explanation Correct answer is Orange, because x is greater than y, so once this condition is true, it will assign Orange to z variable. Print Page Previous Next Advertisements ”;