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 ”;

Kotlin – Strings

Kotlin – Strings ”; Previous Next The Kotlin String data type is used to store a sequence of characters. String values must be surrounded by double quotes (” “) or triple quote (“”” “””). We have two kinds of string available in Kotlin – one is called Escaped String and another is called Raw String. Escaped string is declared within double quote (” “) and may contain escape characters like ”n”, ”t”, ”b” etc. Raw string is declared within triple quote (“”” “””) and may contain multiple lines of text without any escape characters. Example fun main(args: Array<String>) { val escapedString : String = “I am escaped String!n” var rawString :String = “””This is going to be a multi-line string and will not have any escape sequence”””; print(escapedString) println(rawString) } When you run the above Kotlin program, it will generate the following output: I am escaped String! This is going to be a multi-line string and will not have any escape sequence This is optional to specify the data type for a String, Kotlin can understand that the a variable is a String because of the given double or tripple quotes. If you want to create a String variable without assigning the value then you must specify the type while declaring the variable otherwise it will raise an error: fun main(args: Array<String>) { val name : String name = “Zara Ali” println(name) } When you run the above Kotlin program, it will generate the following output: Zara Ali Kotlin String Templates Kotlin string templates are pieces of code that are evaluated and whose results are interpolated into the string. A template expression starts with a dollar sign ($) and may consist of either a name or an expression. fun main(args: Array<String>) { val name : String = “Zara Ali” println(“Name – $name”) // Using template with variable name println(“Name length – ${name.length}”) // Using template with expression. } When you run the above Kotlin program, it will generate the following output: Name – Zara Ali Name length – 8 Kotlin String Object Kotlin String is an object, which contains a number of properties and functions that can perform certain operations on strings, by writing a dot character (.) after the specific string variable. We will see some of the important properties and functions in this chapter, remaining you can find in official documentation of Kotlin latest version. Kotlin String Indexes Kotlin String can be treated as a sequence of characters or you can say String is an array of characters. You can access its element by specifying the index of the element using a square brackets. String indexes start with 0, so if you want to access 4th element of the string then you should specify index as 3 to access the 4th element. Example fun main(args: Array<String>) { val name : String = “Zara Ali” println(name[3]) println(name[5]) } When you run the above Kotlin program, it will generate the following output: a A Kotlin String Length We can use length property of Kotlin string to find out its length. Kotlin function count() also returns the length of a given string. Example fun main(args: Array<String>) { val name : String = “Zara Ali” println(“The length of name :” + name.length) println(“The length of name :” + name.count()) } When you run the above Kotlin program, it will generate the following output: The length of name :8 The length of name :8 Kotlin String Last Index We can use lastIndex property of Kotlin string to find out the index of the last character in the char sequence. If a string is empty then it returns a -1. Example fun main(args: Array<String>) { val name : String = “Zara Ali” println(“The index of last character in name :” + name.lastIndex) } When you run the above Kotlin program, it will generate the following output: The index of last character in name :7 Changing Case of Strings Kotlin provides toUpperCase() and toLowerCase() functions to convert a string into upper case and lower case respectively. Example fun main(args: Array<String>) { val name : String = “Zara Ali” println(“Upper case of name :” + name.toUpperCase()) println(“Lower case of name :” + name.toLowerCase()) } When you run the above Kotlin program, it will generate the following output: Upper case of name :ZARA ALI Lower case of name :zara ali Kotlin String Concatenation We can use either + operator to concatenate two strings, or we can also use plus() function to concatenate two strings. Example fun main(args: Array<String>) { var firstName : String = “Zara ” var lastName : String = “Ali” println(“Full Name :” + firstName + lastName) println(“Full Name :” + firstName.plus(lastName) ) } When you run the above Kotlin program, it will generate the following output: Full Name :Zara Ali Full Name :Zara Ali Trim Characters from a String We can remove first few or last few characters from a string using drop() or dropLast() functions. Example fun main(args: Array<String>) { var name : String = “Zara Ali” println(“Remove first two characters from name : ” + name.drop(2)) println(“Remove last two characters from name : ” + name.dropLast(2)) } When you run the above Kotlin program, it will generate the following output: Remove first two characters from name : ra Ali Remove last two characters from name : Zara A Quotes Inside a String To use quotes inside a string, use single quotes (”): Example fun main(args: Array<String>) { var str1 : String = “That”s it” var str2 : String = “It”s OK” println(“str1 : ” + str1) println(“str2 : ” + str2) } When you run the above Kotlin program, it will generate the following output: str1 : That”s it str2 : It”s OK Finding a String inside a String Kotlin provides indexOf() function to find out a text inside a string. This function returns the index of the first occurrence of a specified text in a string Example fun main(args: Array<String>) { var str : String = “Meditation

Kotlin – Interface

Kotlin – Interface ”; Previous Next In this chapter, we will learn about the interface in Kotlin. In Kotlin, the interface works exactly similar to Java 8, which means they can contain method implementation as well as abstract methods declaration. An interface can be implemented by a class in order to use its defined functionality. We have already introduced an example with an interface in Chapter 6 – section “anonymous inner class”. In this chapter, we will learn more about it. The keyword “interface” is used to define an interface in Kotlin as shown in the following piece of code. interface ExampleInterface { var myVar: String // abstract property fun absMethod() // abstract method fun sayHello() = “Hello there” // method with default implementation } In the above example, we have created one interface named as “ExampleInterface” and inside that we have a couple of abstract properties and methods all together. Look at the function named “sayHello()”, which is an implemented method. In the following example, we will be implementing the above interface in a class. Live Demo interface ExampleInterface { var myVar: Int // abstract property fun absMethod():String // abstract method fun hello() { println(“Hello there, Welcome to TutorialsPoint.Com!”) } } class InterfaceImp : ExampleInterface { override var myVar: Int = 25 override fun absMethod() = “Happy Learning “ } fun main(args: Array<String>) { val obj = InterfaceImp() println(“My Variable Value is = ${obj.myVar}”) print(“Calling hello(): “) obj.hello() print(“Message from the Website– “) println(obj.absMethod()) } The above piece of code will yield the following output in the browser. My Variable Value is = 25 Calling hello(): Hello there, Welcome to TutorialsPoint.Com! Message from the Website– Happy Learning As mentioned earlier, Kotlin doesn’t support multiple inheritances, however, the same thing can be achieved by implementing more than two interfaces at a time. In the following example, we will create two interfaces and later we will implement both the interfaces into a class. Live Demo interface A { fun printMe() { println(” method of interface A”) } } interface B { fun printMeToo() { println(“I am another Method from interface B”) } } // implements two interfaces A and B class multipleInterfaceExample: A, B fun main(args: Array<String>) { val obj = multipleInterfaceExample() obj.printMe() obj.printMeToo() } In the above example, we have created two sample interfaces A, B and in the class named “multipleInterfaceExample” we have implemented two interfaces declared earlier. The above piece of code will yield the following output in the browser. method of interface A I am another Method from interface B Print Page Previous Next Advertisements ”;

Kotlin – Maps

Kotlin – Maps ”; Previous Next Kotlin map is a collection of key/value pairs, where each key is unique, and it can only be associated with one value. The same value can be associated with multiple keys though. We can declare the keys and values to be any type; there are no restrictions. A Kotlin map can be either mutable (mutableMapOf) or read-only (mapOf). Maps are also known as dictionaries or associative arrays in other programming languages. Creating Kotlin Maps For map creation, use the standard library functions mapOf() for read-only maps and mutableMapOf() for mutable maps. A read-only view of a mutable map can be obtained by casting it to Map. Example fun main() { val theMap = mapOf(“one” to 1, “two” to 2, “three” to 3, “four” to 4) println(theMap) val theMutableMap = mutableSetOf(“one” to 1, “two” to 2, “three” to 3, “four” to 4) println(theMutableMap) } When you run the above Kotlin program, it will generate the following output: {one=1, two=2, three=3, four=4} [(one, 1), (two, 2), (three, 3), (four, 4)] Creating Map using HashMap A Kotlin map can be created from Java”s HashMap. Example fun main() { val theMap = HashMap<String, Int>() theMap[“one”] = 1 theMap[“two”] = 2 theMap[“three”] = 3 theMap[“four”] = 4 println(theMap) } When you run the above Kotlin program, it will generate the following output: {four=4, one=1, two=2, three=3} Using Pair while Creating Map We can use Pair() method to create key/value pairs: Example fun main() { val theMap = mapOf(Pair(“one”, 1), Pair(“two”, 2), Pair(“three”, 3)) println(theMap) } When you run the above Kotlin program, it will generate the following output: {one=1, two=2, three=3} Kotlin Properties Kotlin map has properties to get all entries, keys, and values of the map. fun main() { val theMap = mapOf(“one” to 1, “two” to 2, “three” to 3, “four” to 4) println(“Entries: ” + theMap.entries) println(“Keys:” + theMap.keys) println(“Values:” + theMap.values) } When you run the above Kotlin program, it will generate the following output: Entries: [one=1, two=2, three=3, four=4] Keys:[one, two, three, four] Values:[1, 2, 3, 4] Loop through Kotlin Maps There are various ways to loop through a Kotlin Maps. Lets study them one by one: Using toString() function fun main() { val theMap = mapOf(“one” to 1, “two” to 2, “three” to 3, “four” to 4) println(theMap.toString()) } When you run the above Kotlin program, it will generate the following output: {one=1, two=2, three=3, four=4} Using Iterator fun main() { val theMap = mapOf(“one” to 1, “two” to 2, “three” to 3, “four” to 4) val itr = theMap.keys.iterator() while (itr.hasNext()) { val key = itr.next() val value = theMap[key] println(“${key}=$value”) } } When you run the above Kotlin program, it will generate the following output: one=1 two=2 three=3 four=4 Using For Loop fun main() { val theMap = mapOf(“one” to 1, “two” to 2, “three” to 3, “four” to 4) for ((k, v) in theMap) { println(“$k = $v”) } } When you run the above Kotlin program, it will generate the following output: one = 1 two = 2 three = 3 four = 4 Using forEach fun main() { val theMap = mapOf(“one” to 1, “two” to 2, “three” to 3, “four” to 4) theMap.forEach { k, v -> println(“Key = $k, Value = $v”) } } When you run the above Kotlin program, it will generate the following output: Key = one, Value = 1 Key = two, Value = 2 Key = three, Value = 3 Key = four, Value = 4 Size of Kotlin Map We can use size property or count() method to get the total number of elements in a map: Example fun main() { val theMap = mapOf(“one” to 1, “two” to 2, “three” to 3, “four” to 4) println(“Size of the Map ” + theMap.size) println(“Size of the Map ” + theMap.count()) } When you run the above Kotlin program, it will generate the following output: Size of the Map 4 Size of the Map 4 The containsKey() & containsValue() Methods The The containsKey() checks if the map contains a key. The containsValue() checks if the map contains a value. Example fun main() { val theMap = mapOf(“one” to 1, “two” to 2, “three” to 3, “four” to 4) if(theMap.containsKey(“two”)){ println(true) }else{ println(false) } if(theMap.containsValue(“two”)){ println(true) }else{ println(false) } } When you run the above Kotlin program, it will generate the following output: true false The isEmpty() Method The isEmpty() method returns true if the collection is empty (contains no elements), false otherwise. Example fun main() { val theMap = mapOf(“one” to 1, “two” to 2, “three” to 3, “four” to 4) if(theMap.isEmpty()){ println(true) }else{ println(false) } } When you run the above Kotlin program, it will generate the following output: false The get() Method The get() method can be used to get the value corresponding to the given key. The shorthand [key] syntax is also supported. Example fun main() { val theMap = mapOf(“one” to 1, “two” to 2, “three” to 3, “four” to 4) println(“The value for key two ” + theMap.get(“two”)) println(“The value for key two ” + theMap[“two”]) } When you run the above Kotlin program, it will generate the following output: The value for key two 2 The value for key two 2 There is also the function getValue() which has slightly different behavior: it throws an exception if the key is not found in the map. Map Addition We can use + operator to add two or more maps into a single set. This will add second map into first map, discarding the duplicate elements. If there are duplicate keys in two maps then second map”s key will override the previous map key. Example fun main() { val firstMap = mapOf(“one” to 1, “two” to 2, “three” to 3) val secondMap = mapOf(“one” to 10, “four” to 4) val resultMap = firstMap + secondMap println(resultMap) } When you run the above Kotlin program, it will generate the following output: {one=10, two=2, three=3,

Kotlin – Break and Continue

Kotlin – Break and Continue ”; Previous Next Kotlin Break Statement Kotlin break statement is used to come out of a loop once a certain condition is met. This loop could be a for, while or do…while loop. Syntax Let”s check the syntax to terminate various types of loop to come out of them: // Using break in for loop for (…) { if(test){ break } } // Using break in while loop while (condition) { if(test){ break } } // Using break in do…while loop do { if(test){ break } }while(condition) If test expression is evaluated to true, break statment is executed which terminates the loop and program continues to execute just after the loop statment. Example Following is an example where the while loop terminates when counter variable i value becomes 3: fun main(args: Array<String>) { var i = 0; while (i++ < 100) { println(i) if( i == 3 ){ break } } } When you run the above Kotlin program, it will generate the following output: 1 2 3 Kotlin Labeled Break Statement Kotlin label is the form of identifier followed by the @ sign, for example test@ or outer@. To make any Kotlin Expression as labeled one, we just need to put a label in front of the expression. outerLoop@ for (i in 1..100) { // … } Kotlin labeled break statement is used to terminate the specific loop. This is done by using break expression with @ sign followed by label name (break@LabelName). fun main(args: Array<String>) { outerLoop@ for (i in 1..3) { innerLoop@ for (j in 1..3) { println(“i = $i and j = $j”) if (i == 2){ break@outerLoop } } } } When you run the above Kotlin program, it will generate the following output: i = 1 and j = 1 i = 1 and j = 2 i = 1 and j = 3 i = 2 and j = 1 Kotlin Continue Statement The Kotlin continue statement breaks the loop iteration in between (skips the part next to the continue statement till end of the loop) and continues with the next iteration in the loop. Syntax Let”s check the syntax to terminate various types of loop to come out of them: // Using continue in for loop for (…) { if(test){ continue } } // Using continue in while loop while (condition) { if(test){ continue } } // Using continue in do…while loop do { if(test){ continue } }while(condition) If test expression is evaluated to true, continue statment is executed which skips remaning part of the loop and jump to the next iteration of the loop statment. Example Following is an example where the while loop skips printing variable i when its value is 3: fun main(args: Array<String>) { var i = 0; while (i++ < 6) { if( i == 3 ){ continue } println(i) } } When you run the above Kotlin program, it will generate the following output: 1 2 4 5 6 Kotlin Labeled Continue Statement Kotlin labeled continue statement is used to skip the part of a specific loop. This is done by using continue expression with @ sign followed by label name (continue@LabelName). fun main(args: Array<String>) { outerLoop@ for (i in 1..3) { innerLoop@ for (j in 1..3) { if (i == 2){ continue@outerLoop } println(“i = $i and j = $j”) } } } When you run the above Kotlin program, it will generate the following output: i = 1 and j = 1 i = 1 and j = 2 i = 1 and j = 3 i = 3 and j = 1 i = 3 and j = 2 i = 3 and j = 3 Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – What is the purpose of the break statement in Kotlin? A – Break statement is used to come out of the Kotlin program B – Break statement is used to debug a Kotlin program C – Break statement is used to come out of a loop D – None of the above Answer : C Explanation Kotlin break statement is used to come out of a loop. Show Answer Q 2 – What is labeled expression in Kotlin? A – Labeled expression are used to name different expressions in Kotlin B – Labeled expression is an identifier followed by the @ sign C – Labeled expression gives more control to jump the program execution D – All of the above Answer : D Explanation All the given statements about labeled expression are correct. Show Answer Q 3 – We can use continue statement to skip a part of the loop based on certain condition. A – True B – False Answer : A Explanation Yes it is true, continue statement is used to skip a part of the loop and to jump to the next available iteration. Print Page Previous Next Advertisements ”;

Kotlin – Ranges

Kotlin – Ranges ”; Previous Next Kotlin range is defined by its two endpoint values which are both included in the range. Kotlin ranges are created with rangeTo() function, or simply using downTo or (. .) operators. The main operation on ranges is contains, which is usually used in the form of in and !in operators. Example 1..10 // Range of integers starting from 1 to 10 a..z // Range of characters starting from a to z A..Z // Range of capital characters starting from A to Z Both the ends of the range are always included in the range which means that the 1..4 expression corresponds to the values 1,2,3 and 4. Creating Ranges using rangeTo() To create a Kotlin range we call rangeTo() function on the range start value and provide the end value as an argument. Example fun main(args: Array<String>) { for ( num in 1.rangeTo(4) ) { println(num) } } When you run the above Kotlin program, it will generate the following output: 1 2 3 4 Creating Ranges using .. Operator The rangeTo() is often called in its operator form … So the above code can be re-written using .. operator as follows: Example fun main(args: Array<String>) { for ( num in 1..4 ) { println(num) } } When you run the above Kotlin program, it will generate the following output: 1 2 3 4 Creating Ranges using downTo() Operator If we want to define a backward range we can use the downTo operator: Example fun main(args: Array<String>) { for ( num in 4 downTo 1 ) { println(num) } } When you run the above Kotlin program, it will generate the following output: 4 3 2 1 Kotlin step() Function We can use step() function to define the distance between the values of the range. Let”s have a look at the following example: Example fun main(args: Array<String>) { for ( num in 1..10 step 2 ) { println(num) } } When you run the above Kotlin program, it will generate the following output: 1 3 5 7 9 Kotlin range of Characters Ranges can be created for characters like we have created them for integer values. Example fun main(args: Array<String>) { for ( ch in ”a”..”d” ) { println(ch) } } When you run the above Kotlin program, it will generate the following output: a b c d Kotlin reversed() Function The function reversed() can be used to reverse the values of a range. Example fun main(args: Array<String>) { for ( num in (1..5).reversed() ) { println(num) } } When you run the above Kotlin program, it will generate the following output: 5 4 3 2 1 Kotlin until() Function The function until() can be used to create a range but it will skip the last element given. Example fun main(args: Array<String>) { for ( num in 1 until 5 ) { println(num) } } When you run the above Kotlin program, it will generate the following output: 1 2 3 4 The last, first, step Elements We can use first, last and step properties of a range to find the first, the last value or the step of a range. Example fun main(args: Array<String>) { println((5..10).first) println((5..10 step 2).step) println((5..10).reversed().last) } When you run the above Kotlin program, it will generate the following output: 5 2 5 Filtering Ranges The filter() function will return a list of elements matching a given predicate: Example fun main(args: Array<String>) { val a = 1..10 val f = a.filter { T -> T % 2 == 0 } println(f) } When you run the above Kotlin program, it will generate the following output: [2, 4, 6, 8, 10] Distinct Values in a Range The distinct() function will return a list of distinct values from a range having repeated values: Example fun main(args: Array<String>) { val a = listOf(1, 1, 2, 4, 4, 6, 10) println(a.distinct()) } When you run the above Kotlin program, it will generate the following output: [1, 2, 4, 6, 10] Range Utility Functions There are many other useful functions we can apply to our range, like min, max, sum, average, count: Example fun main(args: Array<String>) { val a = 1..10 println(a.min()) println(a.max()) println(a.sum()) println(a.average()) println(a.count()) } When you run the above Kotlin program, it will generate the following output: 1 10 55 5.5 10 Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which of the following is true about Kotlin Ranges? A – Kotlin range is a sequence of values defined by a start, an end, and a step. B – Kotlin range can be created using the rangeTo() and downTo() functions or the .. operator. C – We can use ranges for any comparable type. D – All of the above Answer : D Explanation All the given statements are true about Kotlin Range Show Answer Q 2 – What will be the output of the following program: fun main(args: Array<String>) { val a = 1..20 println(a.average()) } A – This will print 10.5 B – This will raise just a warning C – Compilation will stop with error D – None of the above Answer : A Explanation Function average() is used to get the average of the range values. Show Answer Q 2 – What will be the output of the following program: fun main(args: Array<String>) { val a = 1..20 if( 3 in a){ print( true ) }else{ print( false ) } } A – true B – false C – Compilation will stop with error D – None of the above Answer : A Explanation It will return true because 3 is available in range so in operator will return true. Print Page Previous Next Advertisements ”;

Kotlin – Variables

Kotlin – Variables ”; Previous Next Variables are an important part of any programming. They are the names you give to computer memory locations which are used to store values in a computer program and later you use those names to retrieve the stored values and use them in your program. Kotlin variables are created using either var or val keywords and then an equal sign = is used to assign a value to those created variables. Syntax Following is a simple syntax to create two variables and then assign them different values: var name = “Zara Ali” var age = 19 var height = 5.2 Examples Once a variable is created and assigned a value, later we can access its value using its name as follows: fun main() { var name = “Zara Ali” var age = 19 println(name) println(age) } When you run the above Kotlin program, it will generate the following output: Zara Ali 19 Let”s see one more example where we will access variable values using dollar sign $: fun main() { var name = “Zara Ali” var age = 19 println(“Name = $name”) println(“Age = $age”) } When you run the above Kotlin program, it will generate the following output: Name = Zara Ali Age = 19 Let”s see one more example to display the variable values without using a dollar sign as below: fun main() { var name = “Zara Ali” var age = 19 println(“Name = ” + name) println(“Age = ” + age) } When you run the above Kotlin program, it will generate the following output: Name = Zara Ali Age = 19 Kotlin Mutable Variables Mutable means that the variable can be reassigned to a different value after initial assignment. To declare a mutable variable, we use the var keyword as we have used in the above examples: fun main() { var name = “Zara Ali” var age = 19 println(“Name = $name”) println(“Age = $age”) name = “Nuha Ali” age = 11 println(“Name = $name”) println(“Age = $age”) } When you run the above Kotlin program, it will generate the following output: Name = Zara Ali Age = 19 Name = Nuha Ali Age = 11 Kotlin Read-only Variables A read-only variable can be declared using val (instead of var) and once a value is assigned, it can not be re-assigned. fun main() { val name = “Zara Ali” val age = 19 println(“Name = $name”) println(“Age = $age”) name = “Nuha Ali” // Not allowed, throws an exception age = 11 println(“Name = $name”) println(“Age = $age”) } When you run the above Kotlin program, it will generate the following output: main.kt:8:4: error: val cannot be reassigned name = “Nuha Ali” // Not allowed, throws an exception ^ main.kt:9:4: error: val cannot be reassigned age = 11 ^ Read-only vs Mutable The Mutable variables will be used to define variables, which will keep charging their values based on different conditions during program execution. You will use Read-only variable to define different constant values i.e. the variables which will retain their value throughout of the program. Kotlin Variable Types Kotlin is smart enough to recognise that “Zara Ali” is a string, and that 19 is a number variable. However, you can explicitly specify a variable type while creating it: fun main() { var name: String = “Zara Ali” var age: Int = 19 println(“Name = $name”) println(“Age = $age”) name = “Nuha Ali” age = 11 println(“Name = $name”) println(“Age = $age”) } When you run the above Kotlin program, it will generate the following output: Name = Zara Ali Age = 19 Name = Nuha Ali Age = 11 Soon we will learn more about different data types available in Kotlin which can be used to create different type of variables. Kotlin Variable Naming Rules There are certain rules to be followed while naming the Kotlin variables: Kotlin variable names can contain letters, digits, underscores, and dollar signs. Kotlin variable names should start with a letter or underscores Kotlin variables are case sensitive which means Zara and ZARA are two different variables. Kotlin variable can not have any white space or other control characters. Kotlin variable can not have names like var, val, String, Int because they are reserved keywords in Kotlin. Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Which of the following statements is correct about Kotlin Variables: A – Kotlin variables are used to store the information during program execution. B – Kotlin variables can be read-only (Not changeable) and mutable (Changeable) C – Kotlin read-only variables are defined using val keyword where as mutable variables are defined using var keyword. D – All of the above Answer : D Explanation All the given three statements are correct for Kotlin variables. Show Answer Q 2 – Identify which line of the following program will raise an error: var name = “Zara Ali” val age = 19 name = “Nuha Ali” age = 11 A – First Line B – Second Line C – Third Line D – Last Line Answer : D Explanation At the last line we are trying to change the value of a read-only variable, so it will raise and exception at this line. Show Answer Q 3 – Which one is a wrong variable name in Kotlin A – My Name B – #MyName C – %MyName D – -MyName E – All of the above Answer : E Explanation As per given rules to define a variable name in Kotlin, all the give variable names are invalid Show Answer Q 4 – Which of the following statment is not correct about Kotlin variable A – Kotlin variables are case sensitive. B – Kotlin can differentiate between different datatypes without explicitly specifying them. C – Kotlin variables can be accessed in multiple ways. D – Kotlin variable name can use any Kotlin reserved keyword Answer : D Explanation Last statement is not correct because

Kotlin – Architecture

Kotlin – Architecture ”; Previous Next Kotlin is a programming language and has its own architecture to allocate memory and produce a quality output to the end user. Following are the different scenarios where Kotlin compiler will work differently. Compile Kotlin into bytecode which can run on JVM. This bytecode is exactly equal to the byte code generated by the Java .class file. Whenever Kotlin targets JavaScript, the Kotlin compiler converts the .kt file into ES5.1 and generates a compatible code for JavaScript. Kotlin compiler is capable of creating platform basis compatible codes via LLVM. Kotlin Multiplatform Mobile (KMM) is used to create multiplatform mobile applications with code shared between Android and iOS. Whenever two byte coded files ( Two different programs from Kotlin and Java) runs on the JVM, they can communicate with each other and this is how an interoperable feature is established in Kotlin for Java. Kotlin Native Kotlin/Native is a technology for compiling Kotlin code to native binaries, which can run without a virtual machine. Kotlin/Native supports the following platforms: macOS iOS, tvOS, watchOS Linux Windows (MinGW) Android NDK Many more… Kotlin/Native is primarily designed to allow compilation for platforms where virtual machines are not desirable or possible, for example, embedded devices or iOS. It is easy to include a compiled Kotlin code into existing projects written in C, C++, Swift, Objective-C, and other languages. Quiz Time (Interview & Exams Preparation) Show Answer Q 1 – Kotlin code can be compiled into Javascript code? A – True B – False Answer : A Explanation Yes, Kotlin compiler can convert the .kt file into ES5.1 and generates a compatible code for JavaScript. Show Answer Q 2 – Compiled Kotlin code can be included in which of the following language code? A – Objective-C B – C/C++ C – Swift D – All the above Answer : D Explanation It is easy to include a compiled Kotlin code into existing projects written in C, C++, Swift, Objective-C, and other languages. Print Page Previous Next Advertisements ”;

Kotlin – Useful Resources

Kotlin – Useful Resources ”; Previous Next The following resources contain additional information on Kotlin. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Kotlin Online Training 69 Lectures 4.5 hours Tutorialspoint More Detail Kotlin Masterclass Programming: Android Coding Bible 72 Lectures 5.5 hours Frahaan Hussain More Detail Kotlin Course – Learn Kotlin to develop android apps 50 Lectures 2.5 hours Skillbakery More Detail Kotlin For Android: Beginner To Advanced Featured 96 Lectures 22.5 hours YouAccel More Detail Kotlin Flow For Android Developer 46 Lectures 6 hours Binary IT Solution More Detail Kotlin Course in Tamil 32 Lectures 9 hours Programming Line More Detail Print Page Previous Next Advertisements ”;

Kotlin – Generics

Kotlin – Generics ”; Previous Next Like Java, Kotlin provides higher order of variable typing called as Generics. In this chapter, we will learn how Kotlin implements Generics and how as a developer we can use those functionalities provided inside the generics library. Implementation wise, generics is pretty similar to Java but Kotlin developer has introduced two new keywords “out” and “in” to make Kotlin codes more readable and easy for the developer. In Kotlin, a class and a type are totally different concepts. As per the example, List is a class in Kotlin, whereas List<String> is a type in Kotlin. The following example depicts how generics is implemented in Kotlin. fun main(args: Array<String>) { val integer: Int = 1 val number: Number = integer print(number) } In the above code, we have declared one “integer” and later we have assigned that variable to a number variable. This is possible because “Int” is a subclass of Number class, hence the type conversion happens automatically at runtime and produces the output as “1”. Let us learn something more about generics in Kotlin. It is better to go for generic data type whenever we are not sure about the data type we are going to use in the application. Generally, in Kotlin generics is defined by <T> where “T” stands for template, which can be determined dynamically by Kotlin complier. In the following example, we will see how to use generic data types in Kotlin programming language. Live Demo fun main(args: Array<String>) { var objet = genericsExample<String>(“JAVA”) var objet1 = genericsExample<Int>(10) } class genericsExample<T>(input:T) { init { println(“I am getting called with the value “+input) } } In the above piece of code, we are creating one class with generic return type, which is represented as <T>. Take a look at the main method, where we have dynamically defined its value at the run by proving the value type, while creating the object of this class. This is how generics is interpreted by Kotlin compiler. We will get the following output in the browser, once we run this code in our coding ground. I am getting called with the value JAVA I am getting called with the value 10 When we want to assign the generic type to any of its super type, then we need to use “out” keyword, and when we want to assign the generic type to any of its sub-type, then we need to use “in” keyword. In the following example, we will use “out” keyword. Similarly, you can try using “in” keyword. Live Demo fun main(args: Array<String>) { var objet1 = genericsExample<Int>(10) var object2 = genericsExample<Double>(10.00) println(objet1) println(object2) } class genericsExample<out T>(input:T) { init { println(“I am getting called with the value “+input) } } The above code will yield the following output in the browser. I am getting called with the value 10 I am getting called with the value 10.0 genericsExample@28d93b30 genericsExample@1b6d3586 Print Page Previous Next Advertisements ”;