Kotlin – Constructors A Kotlin constructor is a special member function in a class that is invoked when an object is instantiated. Whenever an object is created, the defined constructor is called automatically which is used to initialize the properties of the class. Every Kotlin class needs to have a constructor and if we do not define it, then the compiler generates a default constructor. A Kotlin class can have following two type of constructors: Primary Constructor Second Constructors A Kotlin class can have a primary constructor and one or more additional secondary constructors. The Kotlin primary constructor initializes the class, whereas the secondary constructor helps to include some extra logic while initializing the class. Kotlin Primary Constructor The primary constructor can be declared at class header level as shown in the following example. class Person constructor(val firstName: String, val age: Int) { // class body } The constructor keyword can be omitted if there is no annotations or access modifiers specified like public, private or protected.. class Person (val firstName: String, val age: Int) { // class body } In this example, we have declared properties through the val keyword to make them read-only. These properties could be defined using keyword var if you need to change their values at later point in time. Initializer Block The primary constructor cannot contain any code. Initialization code can be placed in initializer blocks prefixed with the init keyword. There could be more than one init blocks and during the initialization of an instance, the initializer blocks are executed in the same order as they appear in the class body, interleaved with the property initializers: Following is an example with a usage of initializer block: class Person (val _name: String, val _age: Int) { // Member Variables var name: String var age: Int // Initializer Block init { this.name = _name this.age = _age println(“Name = $name”) println(“Age = $age”) } } fun main(args: Array<String>) { val person = Person(“Zara”, 20) } When you run the above Kotlin program, it will generate the following output: Name = Zara Age = 20 Default Values Kotlin allows to initialize the constructor parameters with some default values. Following is a working example for the same: class Person (val _name: String, val _age: Int=20) { // Member Variables var name: String var age: Int // Initializer Block init { this.name = _name this.age = _age println(“Name = $name”) println(“Age = $age”) } } fun main(args: Array<String>) { val zara = Person(“Zara”) val nuha = Person(“Nuha”, 11) } When you run the above Kotlin program, it will generate the following output: Name = Zara Age = 20 Name = Nuha Age = 11 Kotlin Secondary Constructor As mentioned earlier, Kotlin allows to create one or more secondary constructors for your class. This secondary constructor is created using the constructor keyword. It is required whenever you want to create more than one constructor in Kotlin or whenever you want to include more logic in the primary constructor and you cannot do that because the primary constructor may be called by some other class. Example Take a look at the following example, here we have created a secondary constructor to implement the above example once again: class Person{ // Member Variables var name: String var age: Int // Initializer Block init { println(“Initializer Block”) } // Secondary Constructor constructor ( _name: String, _age: Int) { this.name = _name this.age = _age println(“Name = $name”) println(“Age = $age”) } } fun main(args: Array<String>) { val zara = Person(“Zara”, 20) } When you run the above Kotlin program, it will generate the following output: Initializer Block Name = Zara Age = 20 Secondary constructor do not allow to use val or var with secondary constructor parameters. Now let”s see one example with two secondary constructors: class Person{ // Member Variables var name: String var age: Int var salary:Double // First Secondary Constructor constructor ( _name: String, _age: Int) { this.name = _name this.age = _age this.salary = 0.00 println(“Name = $name”) println(“Age = $age”) } // Second Secondary Constructor constructor ( _name: String, _age: Int, _salary: Double) { this.name = _name this.age = _age this.salary = _salary println(“Name = $name”) println(“Age = $age”) println(“Salary = $salary”) } } fun main(args: Array<String>) { val nuha = Person(“Nuha”, 12) val zara = Person(“Zara”, 20, 2000.00) } When you run the above Kotlin program, it will generate the following output: Name = Nuha Age = 12 Name = Zara Age = 20 Salary = 2000.0 Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – We can define N number of constructors in Kotlin program: Answer : A Explanation Yes we can define a primary constructor and multiple number of secondary constructors in Kotlin program Show Answer Q 2 – Which keyword is used to define a Kotlin constructor: Answer : B Explanation Though the constructor keyword can be omitted if there is no annotations or access modifiers specified. Show Answer Q 3 – Kotlin allows to set default values for the constructor parameters. Answer : A Explanation Yes we can set a default value for any of the constructor parameters. Show Answer Q 4 – Second constructor does not allow to use data types alongwith its parameters. Answer : A Explanation We can not use data types alongwith secondary constructor parameters. Learn online work project make money
Category: kotlin
Kotlin – When Expression Consider a situation when you have large number of conditions to check. Though you can use if..else if expression to handle the situation, but Kotlin provides when expression to handle the situation in nicer way. Using when expression is far easy and more clean in comparison to writing many if…else if expressions. Kotlin when expression evaluates a section of code among many alternatives as explained in below example. Kotlin when matches its argument against all branches sequentially until some branch condition is satisfied. Kotlin when expression is similar to the switch statement in C, C++ and Java. Example fun main(args: Array<String>) { val day = 2 val result = when (day) { 1 -> “Monday” 2 -> “Tuesday” 3 -> “Wednesday” 4 -> “Thursday” 5 -> “Friday” 6 -> “Saturday” 7 -> “Sunday” else -> “Invalid day.” } println(result) } When you run the above Kotlin program, it will generate the following output: Tuesday Kotlin when as Statement Kotlin when can be used either as an expression or as a statement, simply like a switch statement in Java. If it is used as an expression, the value of the first matching branch becomes the value of the overall expression. Example Let”s write above example once again without using expression form: fun main(args: Array<String>) { val day = 2 when (day) { 1 -> println(“Monday”) 2 -> println(“Tuesday”) 3 -> println(“Wednesday”) 4 -> println(“Thursday”) 5 -> println(“Friday”) 6 -> println(“Saturday”) 7 -> println(“Sunday”) else -> println(“Invalid day.”) } } When you run the above Kotlin program, it will generate the following output: Tuesday Combine when Conditions We can combine multiple when conditions into a single condition. Example fun main(args: Array<String>) { val day = 2 when (day) { 1, 2, 3, 4, 5 -> println(“Weekday”) else -> println(“Weekend”) } } When you run the above Kotlin program, it will generate the following output: Weekday Range in when Conditions Kotlin ranges are created using double dots .. and we can use them while checking when condition with the help of in operator. Example fun main(args: Array<String>) { val day = 2 when (day) { in 1..5 -> println(“Weekday”) else -> println(“Weekend”) } } When you run the above Kotlin program, it will generate the following output: Weekday Expression in when Conditions Kotlin when can use arbitrary expressions instead of a constant as branch condition. Example fun main(args: Array<String>) { val x = 20 val y = 10 val z = 10 when (x) { (y+z) -> print(“y + z = x = $x”) else -> print(“Condition is not satisfied”) } } When you run the above Kotlin program, it will generate the following output: y + z = x = 20 Kotlin when with block of code Kotlin when braches can be put as block of code enclosed within curly braces. Example fun main(args: Array<String>) { val day = 2 when (day) { 1 -> { println(“First day of the week”) println(“Monday”) } 2 -> { println(“Second day of the week”) println(“Tuesday”) } 3 -> { println(“Third day of the week”) println(“Wednesday”) } 4 -> println(“Thursday”) 5 -> println(“Friday”) 6 -> println(“Saturday”) 7 -> println(“Sunday”) else -> println(“Invalid day.”) } } When you run the above Kotlin program, it will generate the following output: Second day of the week Tuesday Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which of the following is true about Kotlin when expression? Answer : D Explanation All the mentioned statements are correct about Kotlin when expression. Show Answer Q 2 – Kotlin when can be used as an expression as well as a statement? Answer : A Explanation Yes it is true that Kotlin when can be used as an expression as well as a statement. Show Answer Q 3 – Kotlin when is inspired by which of the following Java statement Answer : A Explanation Kotlin when has very similar syntax and functionality like switch statement available in Java. Learn online work project make money
Kotlin – Booleans Many times we come across a situation where we need to take decision in Yes or No, or may be we can say True or False. To handle such situation Kotlin has a Boolean data type, which can take the values either true or false. Kotlin also has a nullable counterpart Boolean? that can have the null value. Create Boolean Variables A boolean variable can be created using Boolean keyword and this variable can only take the values either true or false: Example fun main(args: Array<String>) { val isSummer: Boolean = true val isCold: Boolean = false println(isSummer) println(isCold) } When you run the above Kotlin program, it will generate the following output: true false In fact, we can create Kotlin boolean variables without using Boolean keyword and Kotlin will understand the variable type based on the assigned values either true or false Kotlin Boolean Operators Kotlin provides following built-in operators for boolean variables. These operators are also called Logical Operators: Operator Name Description Example && Logical and Returns true if both operands are true x && y || Logical or Returns true if either of the operands is true x || y ! Logical not Reverse the result, returns false if the operand is true !x Example Following example shows different calculations using Kotlin Logical Operators: fun main(args: Array<String>) { var x: Boolean = true var y:Boolean = false println(“x && y = ” + (x && y)) println(“x || y = ” + (x || y)) println(“!y = ” + (!y)) } When you run the above Kotlin program, it will generate the following output: x && y = false x || y = true !y = true Kotlin Boolean Expression A Boolean expression returns either true or false value and majorly used in checking the condition with if…else expressions. A boolean expression makes use of relational operators, for example >, <, >= etc. 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 Kotlin and()and or() Functions Kotlin provides and() and or() functions to perform logical AND and logical OR operations between two boolean operands.> These functions are different from && and || operators because these functions do not perform short-circuit evaluation but they always evaluate both the operands. fun main(args: Array<String>) { val x: Boolean = true val y: Boolean = false val z: Boolean = true println(“x.and(y) = ” + x.and(y)) println(“x.or(y) = ” + x.or(y)) println(“x.and(z) = ” + x.and(z)) } When you run the above Kotlin program, it will generate the following output: x.and(y) = false x.or(y) = true x.and(z) = true Kotlin also provides not() and xor() functions to perform Logical NOT and XOR operations respectively. Boolean to String You can use toString() function to convert a Boolean object into its equivalent string representation.> You will need this conversion when assigning a true or false value in a String variable. fun main(args: Array<String>) { val x: Boolean = true var z: String z = x.toString() println(“x.toString() = ” + x.toString()) println(“z = ” + z) } When you run the above Kotlin program, it will generate the following output: x.toString() = true z = true Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which of the following is true about Kotlin Boolean Data type? Answer : A Explanation Kotlin Boolean variable can have only two values either true or false Show Answer Q 2 – What will be the output of the following program: fun main(args: Array<String>) { val x: Boolean = true var y: String y = x } Answer : C Explanation Compilation will stop with type mismatch error because we are trying to store a boolean value into a String variable. We should use toString() to convert Boolean value into string value before we assign it into string variable. Learn online work project make money
Kotlin – Basic Syntax Kotlin Program Entry Point An entry point of a Kotlin application is the main() function. A function can be defined as a block of code designed to perform a particular task. Let”s start with a basic Kotlin program to print “Hello, World!” on the standard output: fun main() { var string: String = “Hello, World!” println(“$string”) } When you run the above Kotlin program, it will generate the following output: Hello, World! Entry Point with Parameters Another form of main() function accepts a variable number of String arguments as follows: fun main(args: Array<String>){ println(“Hello, world!”) } When you run the above Kotlin program, it will generate the following output: Hello, World! If you have observed, its clear that both the programs generate same output, so it is very much optional to pass a parameter in main() function starting from Kotlin version 1.3. print() vs println() The print() is a function in Kotlin which prints its argument to the standard output, similar way the println() is another function which prints its argument on the standard output but it also adds a line break in the output. Let”s try the following program to understand the difference between these two important functions: fun main(args: Array<String>){ println(“Hello,”) println(” world!”) print(“Hello,”) print(” world!”) } When you run the above Kotlin program, it will generate the following output: Hello, world! Hello, world! Both the functions (print() and println()) can be used to print numbers as well as strings and at the same time to perform any mathematical calculations as below: fun main(args: Array<String>){ println( 200 ) println( “200” ) println( 2 + 2 ) print(4*3) } When you run the above Kotlin program, it will generate the following output: 200 200 4 12 Semicolon (;) in Kotlin Kotlin code statements do not require a semicolon (;) to end the statement like many other programming languages, such as Java, C++, C#, etc. do need it. Though you can compile and run a Kotlin program with and without semicolon successfully as follows: fun main() { println(“I”m without semi-colon”) println(“I”m with semi-colon”); } When you run the above Kotlin program, it will generate the following output: I”m without semi-colon I”m with semi-colon So as a good programming practice, it is not recommended to add a semicolon in the end of a Kotlin statement. Packages in Kotlin Kotlin code is usually defined in packages though package specification is optional. If you don”t specify a package in a source file, its content goes to the default package. If we specify a package in Kotlin program then it is specified at the top of the file as follows: package org.tutorialspoint.com fun main() { println(“Hello, World!”) } When you run the above Kotlin program, it will generate the following output: Hello, World! Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Kotlin main() function should have a mandatory parameter to compile the code successfully: Answer : B Explanation No it is not mandatory that Kotlin main() function should always have a parameter. If you need to pass multiple arguments through an array of string then you can use the paremeter like main(args: Array<String>), otherwise it is not required. Show Answer Q 2 – What will be the output of the following Kotlin program fun main() { println(“1”); println(“2”) } Answer : C Explanation Though Kotlin does not recommend using a semicolon in the end of the statement, still if you want to separate two statements in a single line then you can separate them using a semicolon otherwise you will get compile time error. Show Answer Q 3 – Which of the following statement is correct in Kotlin Answer : A Explanation Only A statement is correct here, because we can not run a Kotlin program without main() function, which is called an entry point for Kotlin program. It does not matter if you use print() or println() functions within a Kotlin program. Learn online work project make money
Kotlin – Abstract Classes A Kotlin abstract class is similar to Java abstract class which can not be instantiated. This means we cannot create objects of an abstract class. However, we can inherit subclasses from a Kotlin abstract class. A Kotlin abstract class is declared using the abstract keyword in front of class name. The properties and methods of an abstract class are non-abstract unless we explictly use abstract keyword to make them abstract. If we want to override these members in the child class then we just need to use override keyword infront of them in the child class. abstract class Person { var age: Int = 40 abstract fun setAge() // Abstract Method fun getAge() { // Non-Abstract Method return age } } Abstract classes are always open. You do not need to explicitly use open keyword to inherit subclasses from them. Example Following is a simple example showing a Kotlin Abstract class and its implementation through a child class: abstract class Person(_name: String) { var name: String abstract var age: Int // Initializer Block init { this.name = _name } abstract fun setPersonAge(_age:Int) abstract fun getPersonAge():Int fun getPersonName(){ println(“Name = $name”) } } class Employee(_name: String): Person(_name) { override var age: Int = 0 override fun setPersonAge(_age: Int) { age = _age } override fun getPersonAge():Int { return age } } fun main(args: Array<String>) { val employee = Employee(“Zara”) var age : Int employee.setPersonAge(20) age = employee.getPersonAge() employee.getPersonName() println(“Age = $age”) } When you run the above Kotlin program, it will generate the following output: Name = Zara Age = 20 Here, a class Employee has been derived from an abstract class Person. We have implemented one abstract property and two abstract methods in the child class Employee. Here notable point is that all the abstract members have been overriden in the child class with the help of override, which is a mandatory for a child class if it inherits an abstract class. To summarise, A Kotlin class which contains the abstract keyword in its declaration is known as abstract class. Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); ) But, if a class has at least one abstract method, then the class must be declared abstract. If a class is declared abstract, it cannot be instantiated. To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it. If you inherit an abstract class, you have to provide implementations to all the abstract methods in it. Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which one is true about a Kotlin abstract class : Answer : D Explanation All the given statements are correct about a Kotlin abstract class. Show Answer Q 2 – Which keyword is used to implement the abstract members of a abstract class: Answer : B Explanation We use override keyword to implement abstract members of an abstract class Learn online work project make money
Kotlin – Inheritance Inheritance can be defined as the process where one class acquires the members (methods and properties) of another class. With the use of inheritance the information is made manageable in a hierarchical order. A class which inherits the members of other class is known as subclass (derived class or child class) and the class whose members are being inherited is known as superclass (base class or parent class). Inheritance is one of the key features of object-oriented programming which allows user to create a new class from an existing class. Inheritance we can inherit all the features from the base class and can have additional features of its own as well. All classes in Kotlin have a common superclass called Any, which is the default superclass for a class with no supertypes declared: class Example // Implicitly inherits from Any Kotlin superclass Any has three methods: equals(), hashCode(), and toString(). Thus, these methods are defined for all Kotlin classes. Everything in Kotlin is by default final, hence, we need to use the keyword open in front of the class declaration to make it inheritable for other classes. Kotlin uses operator “:” to inherit a class. Example: Take a look at the following example of inheritance. open class ABC { fun think () { println(“Hey!! i am thiking “) } } class BCD: ABC(){ // inheritence happend using default constructor } fun main(args: Array<String>) { var a = BCD() a.think() } When you run the above Kotlin program, it will generate the following output: Hey!! i am thiking Overriding Methods Now, what if we want to override the think() method in the child class. Then, we need to consider the following example where we are creating two classes and override one of its function into the child class. open class ABC { open fun think () { println(“Hey!! i am thinking “) } } class BCD: ABC() { // inheritance happens using default constructor override fun think() { println(“I am from Child”) } } fun main(args: Array<String>) { var a = BCD() a.think() } When you run the above Kotlin program, it will generate the following output: I am from Child A member marked with keyword override is itself open, so it may be overridden in subclasses. If you want to prohibit re-overriding it then you must make it final as follows: class BCD: ABC() { final override fun think() { println(“I am from Child”) } } Overriding Properties The overriding mechanism works on properties in the same way that it does on methods. Properties declared on a superclass that are then redeclared on a derived class must be prefaced with the keyword override, and they must have a compatible type. open class ABC { open val count: Int = 0 open fun think () { println(“Hey!! i am thinking “) } } class BCD: ABC() { override val count: Int init{ count = 100 } override fun think() { println(“I am from Child”) } fun displayCount(){ println(“Count value is $count”) } } fun main(args: Array<String>) { var a = BCD() a.displayCount() } When you run the above Kotlin program, it will generate the following output: Count value is 100 You can also override a val property with a var property, but not vice versa. This is allowed because a val property essentially declares a get method, and overriding it as a var additionally declares a set method in the derived class. We can also can use the override keyword as part of the property declaration in a primary constructor. Following example makes the use of primary constructor to override count property, which will take default value as 400 in case we do not pass any value to the constructor: open class ABC { open val count: Int = 0 open fun think () { println(“Hey!! i am thinking “) } } class BCD(override val count: Int = 400): ABC() { override fun think() { println(“I am from Child”) } fun displayCount(){ println(“Count value is $count”) } } fun main(args: Array<String>) { var a = BCD(200) var b = BCD() a.displayCount() b.displayCount() } When you run the above Kotlin program, it will generate the following output: Count value is 200 Count value is 400 Derived Class Initialization Order When we create an object of a derived class then constructor initialization starts from the base class. Which means first of all base class properties will be initialized, after that any derived class instructor will be called and same applies to any further derived classes. This means that when the base class constructor is executed, the properties declared or overridden in the derived class have not yet been initialized. open class Base { init{ println(“I am in Base class”) } } open class Child: Base() { init{ println(“I am in Child class”) } } class GrandChild: Child() { init{ println(“I am in Grand Child class”) } } fun main(args: Array<String>) { var a = GrandChild() } When you run the above Kotlin program, it will generate the following output: I am in Base class I am in Child class I am in Grand Child class Access Super Class Members Code in a derived class can call its superclass functions and properties directly using the super keyword: open class Base() { open val name:String init{ name = “Base” } open fun displayName(){ println(“I am in ” + this.name) } } class Child(): Base() { override fun displayName(){ super.displayName() println(“I am in ” + super.name) } } fun main(args: Array<String>) { var a = Child() a.displayName() } When you run the above Kotlin program, it will generate the following output: I am in Base I am in Base Overriding rules If a child class inherits multiple implementations of the same member from its immediate superclasses, then it must override this member and provide its own implementation. This is different from a child class which inherits members from a single parent, in such case case it is not mandatory for the child
Kotlin – Lists Kotlin list is an ordered collection of items. A Kotlin list can be either mutable (mutableListOf) or read-only (listOf). The elements of list can be accessed using indices. Kotlin mutable or immutable lists can have duplicate elements. Creating Kotlin Lists For list creation, use the standard library functions listOf() for read-only lists and mutableListOf() for mutable lists. To prevent unwanted modifications, obtain read-only views of mutable lists by casting them to List. Example fun main() { val theList = listOf(“one”, “two”, “three”, “four”) println(theList) val theMutableList = mutableListOf(“one”, “two”, “three”, “four”) println(theMutableList) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four] [one, two, three, four] Loop through Kotlin Lists There are various ways to loop through a Kotlin list. Lets study them one by one: Using toString() function fun main() { val theList = listOf(“one”, “two”, “three”, “four”) println(theList.toString()) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four] Using Iterator fun main() { val theList = listOf(“one”, “two”, “three”, “four”) val itr = theList.listIterator() 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 theList = listOf(“one”, “two”, “three”, “four”) for (i in theList.indices) { println(theList[i]) } } When you run the above Kotlin program, it will generate the following output: one two three four Using forEach fun main() { val theList = listOf(“one”, “two”, “three”, “four”) theList.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 List We can use size property to get the total number of elements in a list: fun main() { val theList = listOf(“one”, “two”, null, “four”, “five”) println(“Size of the list ” + theList.size) } When you run the above Kotlin program, it will generate the following output: Size of the list 5 The “in” Operator The in operator can be used to check the existence of an element in a list. Example fun main() { val theList = listOf(“one”, “two”, “three”, “four”) if(“two” in theList){ 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 list. Example fun main() { val theList = listOf(“one”, “two”, “three”, “four”) if(theList.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 theList = listOf(“one”, “two”, “three”, “four”) if(theList.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 list, or -1 if the specified element is not contained in the list. Example fun main() { val theList = listOf(“one”, “two”, “three”, “four”) println(“Index of ”two” : ” + theList.indexOf(“two”)) } When you run the above Kotlin program, it will generate the following output: Index of ”two” : 1 The get() Method The get() method can be used to get the element at the specified index in the list. First element index will be zero. Example fun main() { val theList = listOf(“one”, “two”, “three”, “four”) println(“Element at 3rd position ” + theList.get(2)) } When you run the above Kotlin program, it will generate the following output: Element at 3rd position three List Addition We can use + operator to add two or more lists into a single list. This will add second list into first list, even duplicate elements will also be added. Example fun main() { val firstList = listOf(“one”, “two”, “three”) val secondList = listOf(“four”, “five”, “six”) val resultList = firstList + secondList println(resultList) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four, five, six] List Subtraction We can use – operator to subtract a list from another list. This operation will remove the common elements from the first list and will return the result. Example fun main() { val firstList = listOf(“one”, “two”, “three”) val secondList = listOf(“one”, “five”, “six”) val resultList = firstList – secondList println(resultList) } When you run the above Kotlin program, it will generate the following output: [two, three] Slicing a List We can obtain a sublist from a given list using slice() method which makes use of range of the elements indices. Example fun main() { val theList = listOf(“one”, “two”, “three”, “four”, “five”) val resultList = theList.slice( 2..4) println(resultList) } When you run the above Kotlin program, it will generate the following output: [three, four, five] Removing null a List We can use filterNotNull() method to remove null elements from a Kotlin list. fun main() { val theList = listOf(“one”, “two”, null, “four”, “five”) val resultList = theList.filterNotNull() println(resultList) } When you run the above Kotlin program, it will generate the following output: [one, two, four, five] Filtering Elements We can use filter() method to filter out the elements matching with the given predicate. fun main() { val theList = listOf(10, 20, 30, 31, 40, 50, -1, 0) val resultList = theList.filter{ it > 30} println(resultList) } 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 list. fun main() { val theList = listOf(10, 20, 30, 31, 40, 50, -1, 0) val resultList = theList.drop(3) println(resultList) } When you run the above Kotlin program, it will generate the following output: [31, 40, 50, -1, 0] Grouping List Elements We
Kotlin – For Loop
Kotlin – For Loop ”; Previous Next What are loops? Imagine a situation when you need to print a sentence 20 times on your screen. You can do it by using print statement 20 times. What about if you need to print the same sentence one thousand times? This is where we need to use loops to simplify the programming job. Actually, Loops are used in programming to repeat a specific block of code until certain condition is met. Kotlin supports various types of loops and in this chapter we are going to learn Kotlin for loop. Kotlin For Loop Kotlin for loop iterates through anything that provides an iterator ie. that contains a countable number of values, for example arrays, ranges, maps or any other collection available in Kotlin. Kotlin for loop is equivalent to the foreach loop in languages like C#. Kotlin does not provide a conventional for loop which is available in C, C++ and Java etc. Syntax The syntax of the Kotlin for loop is as follows: for (item in collection) { // body of loop } Iterate Through a Range We will study Kotlin Ranges in a separate chapter, for now you should know that Kotlin Ranges provide iterator, so we can iterate through a range using for loop. Following is an example where the loop iterates through the range and prints individual item. To iterate over a range of numbers, we will use a range expression: fun main(args: Array<String>) { for (item in 1..5) { println(item) } } When you run the above Kotlin program, it will generate the following output: 1 2 3 4 5 Let”s see one more example where the loop will iterate through another range, but this time it will step down instead of stepping up as in the above example: fun main(args: Array<String>) { for (item in 5 downTo 1 step 2) { println(item) } } When you run the above Kotlin program, it will generate the following output: 5 3 1 Iterate Through a Array Kotlin Array is another data type which provides iterator, so we can use for loop to iterate through a Kotlin array in the similar way as we did it for the ranges. Following is an example where we used for loop to iterate through an array of strings: fun main(args: Array<String>) { var fruits = arrayOf(“Orange”, “Apple”, “Mango”, “Banana”) for (item in fruits) { println(item) } } When you run the above Kotlin program, it will generate the following output: Orange Apple Mango Banana Let”s see the same example once again, but this time we will iterate through the array using its index. fun main(args: Array<String>) { var fruits = arrayOf(“Orange”, “Apple”, “Mango”, “Banana”) for (index in fruits.indices) { println(fruits[index]) } } When you run the above Kotlin program, it will generate the following output: Orange Apple Mango Banana Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which of the following is true about Kotlin for loop? A – It is used to loop through an iterator. B – Kotlin does not provide conventional for loop like C, C++ or Java. C – Kotlin for loop is equivalent to the foreach loop in languages like C#. D – All of the above Answer : D Explanation All the mentioned statements are correct about Kotlin for loop. Show Answer Q 2 – What will be the last number printed by the following for loop? fun main(args: Array<String>) { for (item in 6 downTo 1 step 2) { println(item) } } A – 6 B – 5 C – 3 D – 2 Answer : D Explanation When we execute above program it prints 6 4 2, so the last number printed by the loop will be 2 Print Page Previous Next Advertisements ”;
Kotlin – Comments
Kotlin – Comments ”; Previous Next A comment is a programmer-readable explanation or annotation in the Kotlin source code. They are added with the purpose of making the source code easier for humans to understand, and are ignored by Kotlin compiler. Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments. Kotlin comments are very much similar to the comments available in Java, C and C++ programming languages. Kotlin Single-line Comments Single line comments in Kotlin starts with two forward slashes // and end with end of the line. So any text written in between // and the end of the line is ignored by Kotlin compiler. Following is the sample Kotlin program which makes use of a single-line comment: // This is a comment fun main() { println(“Hello, World!”) } When you run the above Kotlin program, it will generate the following output: Hello, World! A single line comment can start from anywhere in the program and will end till the end of the line. For example, you can use single line comment as follows: fun main() { println(“Hello, World!”) // This is also a comment } Kotlin Multi-line Comments A multi-line comment in Kotlin starts with /* and end with */. So any text written in between /* and */ will be treated as a comment and will be ignored by Kotlin compiler. Multi-line comments also called Block comments in Kotlin. Following is the sample Kotlin program which makes use of a multi-line comment: /* This is a multi-line comment and it can span * as many lines as you like */ fun main() { println(“Hello, World!”) } When you run the above Kotlin program, it will generate the following output: Hello, Word! Kotlin Nested Comments Block comments in Kotlin can be nested, which means a single-line comment or multi-line comments can sit inside a multi-line comment as below: /* This is a multi-line comment and it can span * as many lines as you like /* This is a nested comment */ // Another nested comment */ fun main() { println(“Hello, World!”) } When you run the above Kotlin program, it will generate the following output: Hello, World! Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which of the following statements is correct about Kotlin Comments: A – Kotlin comments are ignored by the compiler B – Kotlin comments helps programmer to increase the readability of the code C – Kotlin supports nested comments D – All of the above Answer : D Explanation All the given three statements are correct for Kotlin comments. Show Answer Q 2 – What could be the length of a Kotlin Single-line comment: A – 256 characters B – Infinite C – Till the end of the line D – None of the above Answer : C Explanation There is no specification about the length of Kotlin comments, so single-line comment can be as long as a line. A multi-line comment can also span as long as you want. Show Answer Q 3 – Which of the following statements is not correct about Kotlin comments A – Kotlin comments degrade the performance of the Kotlin program B – Kotlin supports single-line and multi-line comments C – Kotlin comments are recommended to make code more readable D – Kotlin comments are very much similar to the comments available in Java, C and C++ Answer : A Explanation Statement A is incorrect because comments never impact a Kotlin program regardless the volume of the comments available in the program because they are ignore by the compiler and they do not cconsider while generating the final bytecode. Print Page Previous Next Advertisements ”;
Kotlin – Discussion
Discuss Kotlin ”; Previous Next Kotlin is a programming language introduced by JetBrains, the official designer of the most intelligent Java IDE, named Intellij IDEA. This is a strongly statically typed 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. Print Page Previous Next Advertisements ”;