Kotlin – Control Flow ”; Previous Next Kotlin flow control statements determine the next statement to be executed. For example, the statements if-else, if, when, while, for, and do are flow control statements. Flow Chart for Control Flow Control flow can be depicted using the following Flow Chart: Kotlin Control Flow Statements This tutorial will take you through all these statements one by one explaining their usage and suitable examples. Kotlin If…Else Expression Kotlin When Expression Kotlin For Loop Kotlin While Loop Kotlin Break and Continue Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which of the following is true about Control Flow Statement? A – Control flow controls the execution of the program B – Loops and Decision Statements are part of control flow C – Control flow is an essential part of modern programming languages D – All of the above Answer : D Explanation All the mentioned statements are correct about control flow. Show Answer Q 2 – Which of the following is a control flow statement in Kotlin? A – String B – Fun C – When D – None of the above Answer : C Explanation Here keyword when is part of the Kotlin Control Flow statements Show Answer Q 3 – If we do not have control flow statements, then it will be almost impossible to write a computer program? A – True B – False Answer : A Explanation Yes it is true, control flow statements are essential part of any programming languages to write a program. Print Page Previous Next Advertisements ”;
Category: kotlin
Kotlin – While Loop
Kotlin – While Loop ”; Previous Next Kotlin while loop executes its body continuously as long as the specified condition is true. Kotlin while loop is similar to Java while loop. Syntax The syntax of the Kotlin while loop is as follows: while (condition) { // body of the loop } When Kotlin program reaches the while loop, it checks the given condition, if given condition is true then body of the loop gets executed, otherwise program starts executing code available after the body of the while loop . Example Following is an example where the while loop continue executing the body of the loop as long as the counter variable i is greater than 0: fun main(args: Array<String>) { var i = 5; while (i > 0) { println(i) i– } } When you run the above Kotlin program, it will generate the following output: 5 4 3 2 1 Kotlin do…while Loop The do..while is similar to the while loop with a difference that the this loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested. Syntax The syntax of the Kotlin do…while loop is as follows: do{ // body of the loop }while( condition ) When Kotlin program reaches the do…while loop, it directly enters the body of the loop and executes the available code before it checks for the given condition. If it finds given condition is true, then it repeats the execution of the loop body and continue as long as the given condition is true. Example Following is an example where the do…while loop continue executing the body of the loop as long as the counter variable i is greater than 0: fun main(args: Array<String>) { var i = 5; do{ println(i) i– }while(i > 0) } When you run the above Kotlin program, it will generate the following output: 5 4 3 2 1 Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which of the following is a loop statement in Kotlin? A – for B – while C – do…while D – All of the above Answer : D Explanation All the mentioned statements are loop statements in Kotlin. Show Answer Q 2 – What is difference between while and do…while loops? A – while loop is faster than do…while loop B – do…while loop is faster than while loop C – while loop checks condition before executing its body, where as do…while checksthe condition after executing its body atleast once. D – There is no difference between two types of loops Answer : C Explanation Statement C is correct about while and do…while loops in Kotlin and in any other modern programming language. Print Page Previous Next Advertisements ”;
Kotlin – Overview
Kotlin – Overview ”; Previous Next What is Kotlin? Kotlin is a new open source programming language like Java, JavaScript, Python etc. It is a high level strongly statically typed language that combines functional and technical part in a same place. Currently, Kotlin mainly targets the Java Virtual Machine (JVM), but also compiles to JavaScript. Kotlin is influenced by other popular programming languages such as Java, C#, JavaScript, Scala and Groovy. The syntax of Kotlin may not be exactly similar to Java Programming Language, however, internally Kotlin is reliant on the existing Java Class library to produce wonderful results for the programmers. Kotlin provides interoperability, code safety, and clarity to the developers around the world. Kotlin was developed and released by JetBrains in 2016. Kotlin is free, has been free and will remain free. It is developed under the Apache 2.0 license and the source code is available on GitHub Why Kotlin? Kotlin is getting high popularity among all level of programmers and it is used for: Cross-platform Mobile applications. Android Application Development. Web Application Development Server Side Applications Desktop Application Development Data science based applications Kotlin works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) and it”s 100% compatible with Java. Kotlin is used by many large companies like Google, Netflix, Slack, Uber etc to develop their Android based applications. The most importantly, there are many companies actively looking for Kotlin developers, especially in the Android development space. Kotlin Version? At the time of writing this tutorial on Aug 3, 2021, The current Kotlin released version is 1.5.21 Kotlin Advantages Following are some of the advantages of using Kotlin for your application development. 1. Easy Language − Kotlin supports object-oriented and functional constructs and very easy to learn. The syntax is pretty much similar to Java, hence for any Java programmer it is very easy to remember any Kotlin Syntax. 2. Very Concise − Kotlin is based on Java Virtual Machine (JVM) and it is a functional language. Thus, it reduce lots of boiler plate code used in other programming languages. 3. Runtime and Performance − Kotlin gives a better performance and small runtime for any application. 4. Interoperability − Kotlin is mature enough to build an interoperable application in a less complex manner. 5. Brand New − Kotlin is a brand new language that gives developers a fresh start. It is not a replacement of Java, though it is developed over JVM. Kotlin has been accepted as the first official language of Android Application Development. Kotlin can also be defined as – Kotlin = Java + Extra updated new features. Kotlin Drawbacks Following are some of the disadvantages of using Kotlin. 1. Namespace declaration − Kotlin allows developers to declare the functions at the top level. However, whenever the same function is declared in many places of your application, then it is hard to understand which function is being called. 2. No Static Declaration − Kotlin does not have usual static handling modifier like Java, which can cause some problem to the conventional Java developer. Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Kotlin has been developed based on the following programming language? A – Python B – Scala C – Java D – None of the Above Answer : C Explanation Kotlin is 100% compatible with Java. Show Answer Q 2 – Kotlin supports object-oriented and functional constructs? A – True B – False Answer : A Explanation Yes, it is true that Kotlin supports object-oriented and functional constructs. Show Answer Q 3 – Kotlin can be used to develop which of the following softwares? A – Mobile Applications B – Client Side Applications C – Server Side Applications D – All of the Above Answer : D Explanation Kotlin can used to develop Mobile Application, Client Side Application, Server Side Application, Desktop Application etc. Show Answer Q 4 – Kotlin is 100% free? A – True B – False C – Not Sure Answer : A Explanation Kotlin is free, has been free and will remain free. It is developed under the Apache 2.0 license and the source code is available on GitHub. Print Page Previous Next Advertisements ”;
Kotlin – Home
Kotlin Tutorial Job Search PDF Version Quick Guide Resources Discussion This Kotlin Tutorial has been prepared by well experienced Kotlin Programmers for the beginners to help them understand the basics of Kotlin Programming Language. After completing this tutorial, you will find yourself at a moderate level of expertise in Kotlin, from where you can take yourself to the next levels. What is Kotlin? Kotlin is a programming language introduced by JetBrains in 2011, the official designer of the most intelligent Java IDE, named Intellij IDEA. Kotlin is free, has been free and will remain free. It is developed under the Apache 2.0 license and the source code is available on GitHub. This is a strongly statically typed general-purpose programming language that runs on JVM. In 2017, Google announced Kotlin is an official language for android development. Kotlin is an open source programming language that combines object-oriented programming and functional features into a unique platform. The content is divided into various chapters that contain related topics with simple and useful examples. Kotlin is a modern programming language that makes developers happier. Kotlin is easy to pick up, so you can create powerful applications immediately. Currently, Kotlin mainly targets the Java Virtual Machine (JVM), but also compiles to JavaScript. Kotlin is influenced by other popular programming languages such as Java, C#, JavaScript, Scala and Groovy. The syntax of Kotlin may not be exactly similar to Java Programming Language, however, internally Kotlin is reliant on the existing Java Class library to produce wonderful results for the programmers. Kotlin provides interoperability, code safety, and clarity to the developers around the world. Kotlin Jobs Kotlin is very high in demand and all major companies are moving towards Kotlin to develop their web and mobile applications. Average annual salary for a Kotlin developer is around $130,000. Though it can vary depending on the location. Following are the great companies who are using Kotlin: Google Amazon Netflix Pinterest Uber Trello Coursera Basecamp Corda JetBrains Many more… So, you could be the next potential employee for any of these major companies. We have develop a great learning material for Kotlin which will help you to prepare for the technical interviews and certification exams based on Kotlin. So, start learning Kotlin using our simple and effective tutorial anywhere and anytime absolutely at your pace. Kotlin Online Compiler We have provided Kotlin Online Compiler which helps you to Edit and Execute the code directly from your browser. Try to click the icon to run the following Kotlin code to print conventional “Hello, World!”. Below code box allows you to change the value of the code. Try to change the value of string variable and run it again to verify the result. fun main() { var string: String = “Hello, World!” // defining a variable println(“$string”) } Quizzes & Assignments This Kotlin tutorial helps you prepare for technical interviews and certification exams. We have provided various quizzes and assignments to check your learning level. Given quizzes have multiple choice type of questions and their answers with short explanation. Following is a sample quiz, try to attempt any of the given answers: Show Answer Q 1 – Kotlin has been developed based on the following programming language? A – Python B – Scala C – Java D – None of the Above Answer : C Explanation Kotlin is 100% compatible with Java. Audience of Kotlin This tutorial has been prepared for the beginners to help them understand the basics of Kotlin programming language. After completing this tutorial, you will find yourself at a moderate level of expertise in Kotlin, from where you can take yourself to the next levels. Prerequisites to Learn Kotlin Before proceeding with this tutorial you should have a basic understanding of Java programming language. Although it is a beginners tutorial, we assume that the readers have a reasonable exposure to any programming environment and knowledge of basic concepts such as variables, commands, syntax, etc. We strongly recommend that you gain some basic knowledge of Java programming language before proceeding with Kotlin programming. Kotlin Questions & Answers You can explore a set of Kotlin Questions and Answers at Kotlin Questions & Answers Frequently Asked Questions about Kotlin There are some very Frequently Asked Questions(FAQ) about Kotlin, this section tries to answer them briefly. What is Kotlin used for? Kotlin is an object-oriented programming language that is used to develop Android-based applications. It can also be used for web development and building server-side applications. Who invented kotlin language? Kotlin language was developed by a Russia based company named JetBrains in 2010. What is the latest version of Kotlin? The latest version of Kotlin is 1.9.0. However, at the time of writing this tutorial, it is in the beta stage. Can I use Kotlin for web development? Yes, you can use Kotlin for web development. There are several plugins and frameworks of Kotlin are available that help in building web applications, such as Kotlin/JS, Kotlin Server Pages, Kotlin Spring boot and so forth. Why Kotlin is the Future of Android App Development? Kotlin is considered the future of Android app development due to the following reasons − It is platform-independent. Seamless interoperability with Java. Code safety. Concise syntax. What does a Kotlin Developer do? Kotlin developers are responsible for planning, designing, and developing apps and software using Kotlin programming language. They contribute in all phases of the development cycle and then test and integrate features as per the need. What is the basic concept of Kotlin? The basic concept of Kotlin includes data types, operators, variables, control structures, nullable & non-nullable variables, generics, delegation, functions, mixing Java and Kotlin. Is Kotlin easy to learn? Yes, Kotlin is very easy to learn, especially if you are already familiar with Java programming language. Our Kotlin tutorial will help you learn Kotlin in clear and concise manner. How to Learn Kotlin? Here is the summarized list of tips which you can follow to learn Kotlin − First and most important
Kotlin – Exception Handling
Kotlin – Exception Handling ”; Previous Next Exception handling is a very important part of a programming language. This technique restricts our application from generating the wrong output at runtime. In this chapter, we will learn how to handle runtime exception in Kotlin. The exceptions in Kotlin is pretty similar to the exceptions in Java. All the exceptions are descendants of the “Throwable” class. Following example shows how to use exception handling technique in Kotlin. fun main(args: Array<String>) { try { val myVar:Int = 12; val v:String = “Tutorialspoint.com”; v.toInt(); } catch(e:Exception) { e.printStackTrace(); } finally { println(“Exception Handeling in Kotlin”); } } In the above piece of code, we have declared a String and later tied that string into the integer, which is actually a runtime exception. Hence, we will get the following output in the browser. val myVar:Int = 12; Exception Handeling in Kotlin Note − Like Java, Kotlin also executes the finally block after executing the catch block. Print Page Previous Next Advertisements ”;
Kotlin – Keywords
Kotlin – Keywords ”; Previous Next Kotlin keywords are predefined, reserved words used in Kotlin programming that have special meanings to the compiler. These words cannot be used as an identifier (variables names, package names, function names etc.) and if used then compiler will raise an exception. Kotlin uses fun keyword to define a function, so if we we will try to use it as a variable name then it will be an exception. For example: fun main() { var fun = “Zara Ali” // Not allowed, throws an exception var age = 19 // Valid variable name println(“Name = $fun”) println(“Age = $age”) } When you run the above Kotlin program, it will generate the following output: main.kt:2:7: error: expecting property name or receiver type var fun = “Zara Ali” // Not allowed, throws an exception ^ main.kt:2:11: error: expecting ”(” var fun = “Zara Ali” // Not allowed, throws an exception ^ main.kt:5:21: error: keyword cannot be used as a reference println(“Name = $fun”) ^ Kotlin keywords have been categorised into three broad categories: (a) Hard Keywords (b) Soft Keywords (c) Modifier Keywords As a good programming practice, it is highly recommended not to use any of the mentioned keywords to name any identifiers while coding in Kotlin. (a) Kotlin Hard Keywords Following is a list of hard keywords and they cannot be used as identifiers: as as? break class continue do else false for fun if in !in interface is !is null object package return super this throw true try typealias typeof val var when while (b) Kotlin Soft Keywords Following is the list of keywords (soft) in the context when they are applicable and can be used as identifiers in other contexts: by catch constructor delegate dynamic field file finally get import init param property receiver set setparam value where (c) Kotlin Modifier Keywords Following is the list of tokens which act as keywords in modifier lists of declarations and can be used as identifiers in other contexts: actual abstract annotation companion const crossinline data enum expect external final infix inline inner internal lateinit noinline open operator out override private protected public reified sealed suspend tailrec vararg Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which of the following is a hard keyword in Kotlin: A – var B – val C – for D – All of the above Answer : D Explanation All the mentioned keywords are from a list of hard keywords in Kotlin. Show Answer Q 2 – Identify which line of the following program will raise an error: var name = “Zara Ali” var age = 19 var class = “6th” var height = 5.3 A – First Line B – Second Line C – Third Line D – Last Line Answer : C Explanation Here 3rd line will raise an error because we have used hard keyword class to define a variable. Show Answer Q 3 – Which statment is incorrect in Kotlin A – We can use Kotlin hard keywords to define any identifier B – Kotlin allows using soft keywords as identifiers based on the context. C – It is a good practice not to use any type of keywords while naming an identifier. D – All of the above statements are incorrect Answer : A Explanation As per given rules, Kotlin hard keywords can not be used to name an identifier. Print Page Previous Next Advertisements ”;
Kotlin – Sealed Class
Kotlin – Sealed Class ”; Previous Next In this chapter, we will learn about another class type called “Sealed” class. This type of class is used to represent a restricted class hierarchy. Sealed allows the developers to maintain a data type of a predefined type. To make a sealed class, we need to use the keyword “sealed” as a modifier of that class. A sealed class can have its own subclass but all those subclasses need to be declared inside the same Kotlin file along with the sealed class. In the following example, we will see how to use a sealed class. Live Demo sealed class MyExample { class OP1 : MyExample() // MyExmaple class can be of two types only class OP2 : MyExample() } fun main(args: Array<String>) { val obj: MyExample = MyExample.OP2() val output = when (obj) { // defining the object of the class depending on the inuputs is MyExample.OP1 -> “Option One has been chosen” is MyExample.OP2 -> “option Two has been chosen” } println(output) } In the above example, we have one sealed class named “MyExample”, which can be of two types only – one is “OP1” and another one is “OP2”. In the main class, we are creating an object in our class and assigning its type at runtime. Now, as this “MyExample” class is sealed, we can apply the “when ” clause at runtime to implement the final output. In sealed class, we need not use any unnecessary “else” statement to complex out the code. The above piece of code will yield the following output in the browser. option Two has been chosen Print Page Previous Next Advertisements ”;
Kotlin – Environment Setup
Kotlin – Environment Setup ”; Previous Next Installing Kotlin command-line compiler One of the key features of Kotlin is that it has interoperability with Java i.e. You can write Kotlin and Java code in the same application. Like Java, Kotlin also runs on JVM therefore to install Kotlin on Windows directly and work with it using the command line You need to make sure you have JDK installed in your system. Verifying the Java installation To verify Java installation − Open command prompt and verify the current version of Java using the javac version command − C:UsersTP>javac -version javac 1.8.0_261 If you doesn’t have Java installed in your system it generates the following error C:UsersKrishna Kasyap>javac -v ”javac” is not recognized as an internal or external command, operable program or batch file. You can install JDK by following the steps given below Installing JDK8 Open the following Oracle Java Downloads page. Click on the JDK Download link under Java SE 8 section. This will redirect to the page that contains JDK software for various platforms, select the desired version (.exe) and download it. After downloading the file JDK file (assume we have downloaded jdk_windows-x64_bin.exe), start the installation by running it. By default, Java will be installed in the path C:Program FilesJavajdk1.8.0_301 you can change the path by clicking on the Change… button. After the completion of the installation click on the Close button. Kotlin Command line compiler Kotlin command line compiler is available at the JetBrains Kotlin GitHub releases page. Download the latest version. Unzip the downloaded file and place it in the desired folder. The Bin directory of the downloaded folder contains all the binary files to run Kotlin. Now, set Path environment variable to this folder. Setting the Path variable Right click on My computer or This PC, select Properties. Click on Advanced System Settings. Then, click on the Environment Variables… button. In the Environment Variables window, under System Variables select the Path variable and edit the variables using the Edit… button. Click on the New button and add the path of the bin folder of installed JDK and Kotlin folders. To verify the installation, open command prompt and type java or javac command, if your installation is successful, you can see the output as shown below: Setting Kotlin environment using IntelliJ IDEA Kotlin is developed by the JetBrains that develops IDEs like AppCode, CLion, DataGrip, DataSpell, GoLand, IntelliJ IDEA etc. The IntelliJ IDEA internally have Kotlin plugin bundled with it. To develop Kotlin download and install IntelliJ. To install a recent version of IntelliJ IDEA: Open JetBrains Downloads page, you can download the free community edition. If you run the downloaded file, it starts the installation process. Proceed with the installation by providing the required details and finally complete the installation. The Plugins tab of IntelliJ displays all the available plugins. By default, Kotlin plugin is activated, in any case if it is not activated. Open the plugin tab, search for Kotlin and install it. Creating first application To create first application, click on NewProject. Select Kotlin/JVM and click Next. Name the project and select the desired location. Now, create a new Kotlin file under the source(src) folder and let’s name it as Test. You can create a sample function as shown below. You can run this by pressing Ctrl + Shift + F10. Setting Kotlin environment using Eclipse You can also execute Kotlin programs in eclipse to do so, you need to have “Eclipse IDE for Java developers” installed in your system. To do so, follow the steps given below. Download the latest version of eclipse installer from the page: https://www.eclipse.org/downloads/ Run the downloaded file and click on the Eclipse IDE for Java developers. Select the installation directory and click on install. Open eclipse in the Help menu select Eclipse Marketplace. Search for Kotlin and check all the matches and when you find Kotlin click on Install. Creating a Kotlin application in eclipse Once you have installed Kotlin plugin in your eclipse to create your first application. In the File menu click on Project. This will take you to Select a wizard. Under Kotlin (dropdown menu), click on select “Kotlin Project” and click on the “Next” button. Then, enter the desired name for the application and click on Next. Right click on the src folder of the created project click on other. Select the Kotlin File wizard click on Next and name the file as Hello.kt. Your development environment is ready now. Go ahead and add the following piece of code in the “Hello.kt” file. fun main(args: Array) { println(“Hello, World!”) } Run it as a Kotlin application and see the output in the console as shown in the following screenshot. For better understanding and availability, we will be using our coding ground tool. Print Page Previous Next Advertisements ”;
Kotlin – Class and Objects
Kotlin – Class and Objects ”; Previous Next Kotlin supports both functional and object-oriented programming. While talking about functional features of Kotlin then we have concepts like functions, higher-order functions and lambdas etc. which represent Kotlin as a functional language. Kotlin also supports Object Oriented Programming (OOP) and provides features such as abstraction, encapsulation, inheritance, etc. This tutorial will teach you all the Kotlin OOP features in simple steps. Object oriented programming (OOP) allows us to solve the complex problems by using the objects. Kotlin Classes A class is a blueprint for the objects which defines a template to be used to create the required objects. Classes are the main building blocks of any Object Oriented Programming language. A Kotlin class is defined using the class keyword. Following is the syntax to create a Kotlin Class: A Kotlin class declaration is similar to Java Programmig which consists of a class header and a class body surrounded by curly braces. class ClassName { // Class Header // // Variables or data members // Member functions or Methods // … … } By default, Kotlin classes are public and we can control the visibility of the class members using different modifiers that we will learn in Visibility Modifiers. Kotlin Objects The objects are created from the Kotlin class and they share the common properties and behaviours defined by a class in form of data members (properties) and member functions (behaviours) respectively. The syntax to declare an object of a class is: var varName = ClassName() We can access the properties and methods of a class using the . (dot) operator as shown below: var varName = ClassName() varName.property = <Value> varName.functionName() Example Following is an example where we will create one Kotlin class and its object through which we will access different data members of that class. class myClass { // Property (data member) private var name: String = “Tutorialspoint.com” // Member function fun printMe() { print(“The best Learning website – ” + name) } } fun main(args: Array<String>) { val obj = myClass() // Create object obj of myClass class obj.printMe() // Call a member function using object } The above piece of code will yield the following output in the browser, where we are calling printMe() method of myClass with the help of its own object obj. The best Learning website – Tutorialspoint.com Kotlin Nested Class By definition, when a class has been created inside another class, then it is called as a nested class. Kotlin nested class is by default static, hence, it can be accessed without creating any object of that class but with the help of . dot operator. Same time we cannot access members of the outer class inside a nested class. Following is the simple syntax to create a nested class: class OuterClass{ // Members of Outer Class class NestedClass{ // Members of Nested Class } } Now we can create an object of nested class as below: val object = OuterClass.NestedClass() Example Following is the example to show how Kotlin interprets a nested class. fun main(args: Array<String>) { val obj = Outer.Nested() print(obj.foo()) } class Outer { class Nested { fun foo() = “Welcome to The TutorialsPoint.com” } } When you run the above Kotlin program, it will generate the following output: Welcome to The TutorialsPoint.com Kotlin Inner Class When a nested class is marked with a keyword inner, then it will be called as an Inner class. An inner class can be accessed by the data member of the outer class. Unlike a nested class, inner class can access members of the outer class. We cannot directly create an object of the inner class but it can be created using the outer class object. Following is the simple syntax to create an inner class: class OuterClass{ // Members of Outer Class class inner InnerClass{ // Members of Inner Class } } Now we can create an object of inner class as below: val outerObj = OuterClass() val innerObj = outerObj.InnerClass() Example Following is the example to show how Kotlin interprets an inner class. fun main(args: Array<String>) { val obj = Outer().Inner() print(obj.foo()) } class Outer { private val welcomeMessage: String = “Welcome to the TutorialsPoint.com” inner class Inner { fun foo() = welcomeMessage } } When you run the above Kotlin program, it will generate the following output: Welcome to The TutorialsPoint.com Anonymous Inner Class Anonymous inner class is a pretty good concept that makes the life of a programmer very easy. Whenever we are implementing an interface, the concept of anonymous inner block comes into picture. The concept of creating an object of interface using runtime object reference is known as anonymous class. Example Following is the example to show how we will create an interface and how we will create an object of that interface using Anonymous Inner class mechanism. fun main(args: Array<String>) { var programmer :Human = object:Human { // Anonymous class override fun think() { // overriding the think method print(“I am an example of Anonymous Inner Class “) } } programmer.think() } interface Human { fun think() } When you run the above Kotlin program, it will generate the following output: I am an example of Anonymous Inner Class Kotlin Type Aliases Kotlin Type Aliases means a way to give an alternative name to an existing type. Type alias provides a cleaner way to write a more readable code. Consider a following function which returns a user info first name, last name and age: fun userInfo():Triple<String, String, Int>{ return Triple(“Zara”,”Ali”,21) } Now we can a type alias for the given Triple as follows: typealias User = Triple<String, String, Int> Finally the above function can be written as below, which looks more clean than above code: fun userInfo():User{ return Triple(“Zara”,”Ali”,21) } Example Following is the complete working example to show the usage of type alias in Kotlin: typealias User = Triple<String, String, Int> fun main() { val obj = userInfo() print(obj) } fun userInfo():User{ return
Kotlin – Collections
Kotlin – Collections ”; Previous Next Collections are a common concept for most programming languages. A collection usually contains a number of objects of the same type and Objects in a collection are called elements or items. The Kotlin Standard Library provides a comprehensive set of tools for managing collections. The following collection types are relevant for Kotlin: Kotlin List – List is an ordered collection with access to elements by indices. Elements can occur more than once in a list. Kotlin Set – Set is a collection of unique elements which means a group of objects without repetitions. Kotlin Map – Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value. Kotlin Collection Types Kotlin provides the following types of collection: Collection or Immutable Collection Mutable Collection Kotlin Immutable Collection Immutable Collection or simply calling a Collection interface provides read-only methods which means once a collection is created, we can not change it because there is no method available to change the object created. Collection Types Methods of Immutable Collection List listOf() listOf<T>() Map mapOf() Set setOf() Example fun main() { val numbers = listOf(“one”, “two”, “three”, “four”) println(numbers) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four] Kotlin Mutable Collection Mutable collections provides both read and write methods. Collection Types Methods of Immutable Collection List ArrayList<T>() arrayListOf()mutableListOf() Map HashMaphashMapOf()mutableMapOf() Set hashSetOf()mutableSetOf() Example fun main() { val numbers = mutableListOf(“one”, “two”, “three”, “four”) numbers.add(“five”) println(numbers) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four, five] Note that altering a mutable collection doesn”t require it to be a var. Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which of the following is true about Kotlin Collections? A – Kotlin provides mutable and immutable collection B – List, Set and Map are Kotlin Collections C – Kotlin Map can store values in Key-Value pairs D – All of the above Answer : D Explanation All the given statements are true about Kotlin Collections Show Answer Q 2 – What will be the output of the following program: fun main() { val numbers = listOf(“one”, “two”, “three”, “four”) numbers = listOf(“five”) } A – This will print 0 B – This will raise just a warning C – Compilation will stop with error D – None of the above Answer : C Explanation This will stop with error: val cannot be reassigned. Show Answer Q 2 – Which statement is not correct? A – Kotlin List can have duplicate values B – Kotlin Set can not have duplicate values C – Immutable collection does not provide methods to change/update the collection. D – Kotlin does not provide collection types: sets, lists, and maps Answer : D Explanation Kotlin provides collection types: sets, lists, and maps Print Page Previous Next Advertisements ”;