Kotlin
About the Tutorial Tutorial Kotlin is a programm programming ing language language introduced by Jet Brains, Brains, t he offic ial designer designer of the most most intelligent intelligent Java IDE, IDE, named named Intellij Intellij IDEA. IDEA. This is is a strongly stat ically typed ty ped language language t hat hat runs on JVM. In 2017, Google announced Kotlin is an official language for android development. Kotlin is an open source program programmi ming ng language language that c ombines ombines objec t - oriente oriented d programm programming ing and functional funct ional features into into a unique unique platform platf orm.. The content cont ent is divided into various various c hapters that c ontain related related t opics with simple simple and useful useful example example s .
Audience This tut orial orial has has been prepared prepared for the beginners beginners to help them understa understand nd the basics of Kotlin programm programming ing language. language. Aft er c ompleting ompleting this tut orial, orial, you will find find yourself yourself at a moderate level of expertise expertise in Kotlin, Kotlin, from where you can t ake yourself t o the next levels.
Prerequisites Before proc eeding with this t his tut orial orial you should should have a basic basic understanding of Java programming language. Although it is is a beginners’ beginners’ tut orial, orial, we assume assume that the readers have a reasonable reasonable exposure exposure to any program programmi ming ng environm environment and knowledge knowledge of basic c oncepts once pts such as variables, variables, c omm ommands, syntax, synt ax, etc et c . We strongly recommend recommend that you gain gain some some basic knowledge knowledge of Java programmi programming ng language language bef ore proc proceed eeding ing with Kotlin Kotlin programming.
Copyrigh Copyrightt & Disclaime Disclaimer r Copyright Copyright
2017 by Tutorials Point (I) Pvt. Ltd.
All the c ontent and graphics graphics published published in this e- book are the property property of Tut orials orials Point Point (I) Pvt. Pvt . Ltd. The user of t his e- book is prohibi prohibite ted d to reuse, ret retain, ain, copy, copy , distribute distribute or republish republish any c ontents or a part part of cont ents of of this e -book in any mann manner er without writt writt en c onsent onsent of the t he publisher. publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides provides no guarant guarant ee regarding regarding the acc ac c uracy, t imelin imeliness ess or completeness completeness of our website or its cont ents including including this tutorial. t utorial. If If you discover discov er any error errors s on our website or in this tutorial, please notify us at
[email protected]
i
Kotlin
Table of Contents Abou Ab outt the th e Tutor Tut orial ial .............................................................................................. ......................................................................................................................................................... ........................................................... i Audie Au die nce ........................................................................................................................................ ................................. i Prerequisites .................................................................................................................................................................. i Copyr Co pyr ight igh t & Dis claim cl aime e r ................................................................................................ ................................................................................................................................................ ................................................ i Table Tab le of Cont Co nte e nts nt s ............................................................................................... ......................................................................................................................................................... .......................................................... ii
Advant Advan t ages & Disadv Dis advant antage age s ............. ................... ............. .............. ............. ............ ............ ............. ............. ............. ............. ............ ............ ............. .............. ............. ............ ............. ............. ..........1 ....1
Numbers.........................................................................................................................................................................8 Characters ......................................................................................................................................................................9 Boole Boo lea a n ................................................................................................ ....................................................................................................................................................................... ....................................................................... 10 Strings .......................................................................................................................................................................... 10 Array Ar rayss ................................................................................................ ........................................................................................................................................................................... ........................................................................... 11 Colle Co llect ction ion s ............................................................................................ .................................................................................................................................................................. ...................................................................... 12 Range Ran gess ................................................................................................ ......................................................................................................................................................................... ......................................................................... 13
If - E lse ......................................................................................................................................................................... ........................................................................... .............................................................................................. 15 Use of Whe n ................................................................................................ ............................................................................................................................................................... ............................................................... 16 For Loop....................................................................................................................................................................... 17 While Whi le Loop Lo op and an d Do-W hile Loop Lo op ............ .................. ............. ............. ............. ............. ............. ............. ............ ............. ............. ............. ............. ............ ............. ............. ............ ............. ........... .... 18 Use of Ret urn, ur n, Bre ak, Con Conti tin n ue ............ .................. ............. ............. ............. ............. ............ ............. ............. ............. ............. ............ ............. ............. ............. ............. ............ ............. ............ ..... 20
ii
Kotlin
Ne sted st ed Class Cl ass ................................................................................................ ............................................................................................................................................................... ............................................................... 24 Inner Class................................................................................................................................................................... 25 Anon An onym ymou ouss Inne r Cl ass ................................................................................................ ............................................................................................................................................ ............................................ 26 Type Ali ases ase s ................................................................................................. ................................................................................................................................................................ ............................................................... 27
Funct Fu nction ion Exte Ext e nsion nsi on ............................................................................................. .................................................................................................................................................... ....................................................... 39 Obje Ob ject ct Ext e nsio nsi o n ................................................................................................ ....................................................................................................................................................... ....................................................... 40
Prope Pr opert rt y Deleg Del egatio ation n ............. ................... ............. .............. ............. ............ ............ ............. ............. ............. ............. ............ ............ ............. .............. ............. ............ ............. .............. ............. ............ .......... .... 47
L ambda am bda Fun Fu n ction ct ion ................................................................................................ ....................................................................................................................................................... ....................................................... 51 Inline Inli ne Fu nction nct ion ................................................................................................ ........................................................................................................................................................... ........................................................... 51
iii
1.
Kotlin - Overview
Kotlin
Kotlin is a new new open source programm programming ing language language like like J ava, JavaSc ript ript,, etc . It is a high high level strongly statically typed language that combines functional and technical part in a same same place. Currently, Currently, Kotlin Kotlin targets ta rgets Java and JavaScri JavaSc ript. pt. It runs runs on JVM. Kotlin is influenc influenc ed by other program programmi ming ng languages languages such as Java, Scala, Groovy, Gosu, etc et c . The syntax of Kotlin Kotlin may not be exact ly simil similar ar to JAVA, however, internally internally Kotlin Kotlin is reliant reliant on the existing existing Java Class Class librar library y to produce produce wonderful results for the programm programme e rs . Kotlin provides provides interoperabili interoperability ty,, c ode safet y, and c larity larity to the developers around around t he world.
Advantages & Di Disadvantages Following are some of the advantages of using Kotlin for your application development. Easy Language: Language : Kotli ot lin n is a funct ional language language and very easy to learn. learn. The syntax is is prett y much simil similar ar to Java, hence it is is very easy to rem remem ember. ber. Kotli ot lin n is more more expressive expressive , which whic h makes your c ode more readable and understandable. underst andable. Concise: Concise : Kotlin is based on JVM and it is a functional language. Thus, it reduce lots of boiler boiler plate c ode used in in other ot her programm programming ing languages. languages. Runtime and Performance : Bett er performanc performance e and a nd small small runtim runt ime. e. Interoperability: Interoperability : Kotlin is mature at ure enough e nough t o build an interoperable inte roperable applicat applic ation ion in a less less complex manner. Brand New: New: Kotli ot lin n is a brand brand new language t hat gives developers a fresh st art. It is not a replacem replacement ent of Java, t hough hough it is developed developed over JVM. JVM. It is is acc epted as t he first first official language language of android android development. development. Kotlin c an be defined as - Kotlin= JAVA +extra +extra updated updat ed new feat ures. ures. Following are some of the disadvantages of Kotlin. Namespace declaration: declaration : Kotlin Kotlin allows allows developers de velopers to declar dec lare e t he funct ions at the top level. However, whenever the same same f unct ion is declared in many places of your applicat applicat ion, then it is hard to understand understand which whic h function funct ion is being c alled. alled. No Static Declaration: Declaration : Kotlin does not have usual usual st atic at ic handling handling modifier like like J ava, which can cause some some problem problem to the c onventional Java developer.
1
2.
Kotlin - Environment Setup
Kotlin
In this chapt er, we will will set up our our local environm environment ent to start st art with Kotli ot lin n programm programmii ng . However, we w e already already have set up Kot Kotli lin n environment environment online online (coding (c oding ground), ground), so that that c ompil ompilat ation ion and execution execut ion of all availabl available e examples examples online online c an be easier. This gives gives confidence as you c an check the result result with different different options. options. Feel free t o modi modify fy any example example and execut e it online. online. Following is the screenshot sc reenshot of our online online c oding ground. ground.
2
Kotlin
However, if you still want to use Kotlin offline in your loc local al syst em, em, t hen you need to exec exec ute the following following steps ste ps to configure your local loc al workspace. workspace. Step 1: 1: Java 8 installation. Kotlin runs runs on JVM, henc e. it is really really nec essary to use JDK 8 for your local Kotlin development. development. Please refer to the t he offic ial website of oracle t o download and inst install all JDK JDK 8 or an above version. Y ou might have to t o set t he environ environm ment variable variable for JAVA such that it it c an work properly. properly. To verify verify your inst install allat ation ion in Windows operating o perating syste m, hit “java – version” in t he comm command prompt prompt and as an output it will show you yo u the java versio n installed in your system. Step 2: 2: IDE installation. There are a num number ber of ID IDE available available over the internet. Y ou can use any of your choice. c hoice. You can find the download link of different IDE IDE in the following following table. IDE IDE Name NetBeans
Installation Installa tion Link https://netbeans.org/downloads/
Eclipse
https://www.eclipse.org/downloads/
Intellij
https://www.jetbrains.com/idea/download/#section=windows
It is always always recommended recommended to use use the t he rec rec ent software version to t o drag out maxim maximum um fac ility ility from it.
3
Kotlin
Step 3: 3: Configuring Eclipse. Open Ecli Ec lipse pse and go to t o “Eclipse Market Place”. Place ”. You will will find the following screen.
Search for Kotlin Kotlin in the search box and install t he same same in your local syst em. em. It might might take ta ke some some time time depending on t he internet speed. spee d. You may may have to t o restart your y our Ecli Ec lipse, pse, onc e it it is successfully installed. 4
Kotlin
Step 4: 4: Kotlin Project. Once Eclipse is succ essfully restarted restarte d and Kotlin Kotlin is installed, installed, you will be able able to creat e a Kotlin projec projec t on the fly. Go Go t o File New Others and select “Kotlin “Kotlin projec projec t” from the list.
Once the project setup is done, you can create a Kotlin file under “SRC” folder. Left -click on the “Src” folder and hit “new” . You will get an option for Kotlin file, otherwise you may have to search from t he “others”. “ot hers”. Once t he new file file is created, your project project direc directory tory will be look like the following.
5
Kotlin
Your development development environm environment is ready ready now. Go ahead and add add the t he following following piece of code in the “Hel the “Hello.kt” lo.kt” file . fun main(args: main(args: A rray
) rray) { println("Hello, println("Hello, Wo rld!") rld!") }
Run it as a Kotlin application and see the output in the console as shown in the following screenshot. sc reenshot. For bette bet terr underst understandin anding g and availability, availability, we will will be using our coding ground ground tool.
6
3.
Kotlin Kotli n - Architecture
Kotlin
Kotlin is a programm programming ing language language and has its its own architec ture to allocat allocat e mem memory ory and produc produc e a quali quality ty output t o the end user. user. Following Following are t he different sc enarios enarios where Kotlin c ompil ompiler er will work diffe differently, rently, w henever it is targeting diffe different rent ot her kind kind of languages such as Java and JavaSc ript. ript. Kotlin compil compiler er creates a byte c ode and that byte code can run run on t he JVM, which which is exactly equal to the byte code generated by the Java .class file. .class file. Whenever two byte coded file runs runs on t he JVM, they t hey can comm communic unic ate with eac h other ot her and t his is how how an interoperabl interoperabl e feature is established in Kotlin for Java.
Whenever Kotlin targets target s JavaSc ript, ript, the Kot Kotli lin n c ompil ompiler er c onverts the .kt .kt file into ES5.1 and generates a com c ompatible patible c ode for JavaSc ript ript.. Kotlin Kotlin c ompil ompiler er is c apable of creating c reating platform basis compatible codes via LLVM.
7
4.
Kotlin - Basic Types
Kotlin
In this chapter, chapt er, we will learn learn about t he basic basic dat a types ty pes available available in Kot Kotli lin n programmi programming ng language.
Numbers The representat representat ion of num numbers in Kotlin Kotlin is prett y sim similar ilar to Java, Jav a, howeve however, r, Kotlin Kotlin does not not allow allow internal inte rnal c onversion of different data types. t ypes. Following Following t able lists lists different variable lengths for different numbers. numbers. Type Double
Size 64
Float Long Int
32 64 32
Short Byte
16 8
In the following following example, example, we will see how Kotlin Kotlin works works with w ith different dat a types. ty pes. Please enter ente r the following following set of code in our coding c oding ground. ground. fun main(args: main(args: A rray) rray) { val a: Int = 10000 val d: Double = 100.00 val f: Float Float = 100.00f val l: Long = 1000000004 val s: Short Short = 10 val b: Byte = 1 println("Your Int Value is "+a); println("Your println("Your Double
Value is "+d);
println("Your println("Your Float Value is "+f); println("Your println("Your Long Value is "+ l); println("Your println("Your Short Value is "+s); println("Your println("Your Byte Value is "+ b); }
8
Kotlin
When you run run tthe he above piece of code in in t he c oding ground, ground, it will generate t he following output in in the web console. console.
Characters Kotlin represents character using char. char. Character should be declared in a single quote like ‘c’. Please ent er the following following c ode in our coding ground ground and see how how Kotlin interpr inte rpret et s the c haract er variable. variable. Charac Characte terr variable variable c annot be declared lik like e number number variables. variables. Kotlin variabl variable e can be declared declared in two ways - one using “var “var”” and another using “val “ val”. ”. fun main(args: main(args: A rray) rray) { val letter: Char // defining a variable letter letter = 'A'
// Assigning a value to it
println("$letter")
}
The above piec piec e of c ode will yield t he following following output in the browser output window.
9
Kotlin
Boolean Boolean is very simple simple like like ot o t her programm programming ing languages. We have only two tw o value s for Boolean – either true or false. In the following following example, example, we will will see s ee how Kotlin interprets interpret s Boolean. fun main(args: main(args: A rray) rray) { val letter: Boolean // defining a variable letter letter = true
// Assinging a value to it
println("Your character value is "+"$letter")
}
The above piece of code will will yield the following following output in the browser. browser.
Strings Strings are charact er arrays. arrays. Like Like Java, J ava, t hey are im immutab le in nature. We have two tw o kind kind s of st ring ring available in Kotlin - one is is c alled alled raw String String and another is called escaped String. String. In the following following example, example, we will will make make use of these strings. strings. fun main(args: main(args: A rray) rray) { var rawString rawString :String ="I am Raw String!" val escapedString escapedString : String ="I am escaped String!\n" println("Hello!"+escapedString) println("Hey!!"+rawString)
}
The above example example of esc aped String allows t o provide provide extra line line space spac e after aft er the first first print statement. Following will be the output in the browser.
10
Kotlin
Arrays Arrays Arrays are a c ollec ollec tion of homogeneous homogeneous data. Like Like Java, Java , Kotlin Kotlin supports supports arr a rrays ays of different data types. In the following following example, example, we will will make make use of different arrays. fun main(args: main(args: A rray) rray) { val numbers: numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
println("Hey!! println("Hey!! I am a rray Example"+numbers[2]) Example"+numbers[2])
}
The above piece of code yields t he following following output . The indexing indexing of the array array is simil similar ar to other programm programming ing languages. languages. Here, Here, we are searching for a sec ond index, index, whose value is is “3”.
11
Kotlin
Collections Collec Collec tion is a very important important part of the data struct st ructure, ure, which makes makes the soft ware development development easy for engineers. engineers. Kotlin Kotlin has two ty pes of coll c ollec ec tion - one is is immutable collection collection (which means lists, maps and sets that cannot be editable) and another is mutable collection collection (this type of collection is editable). It is very important to keep in mind the type ty pe of c ollect ion used in your applic applic ation, as Kot Kotli lin n syste sy stem m does not represent represent any specific difference in them. fun main(args: main(args: A rray) rray) { val numbers: MutableList MutableList = mutableListOf(1, 2, 3) //mutable List val readOnlyView: readOnlyView: List List = numbers numbers println("my println("my immutable immutable list--"+numbers)
// immutable list // prints "[1, 2, 3]"
numbers.add(4) println("my println(" my immutable list after addition --"+numbers) "[1, 2, 3, 4]"
// prints prin ts
println(readOnlyView) readOnlyView.clear() readOnlyV iew.clear()
// -> does not compile
// gives error }
The above piec piec e of code will will yield the following following output in t he browser. It gives an a n error error when we try t o clear the mutable list list of c ollec ollection. tion.
In collection, Kotlin provides some useful methods such as first(), first(), last(), last(), filter(), filter(), etc. All these methods et hods are self- desc riptive riptive and easy to implem implement ent . Moreover, Kotli ot lin n foll f ollows ows t he same same struct st ructure ure such as Java while while implem implementin enting g c ollect ion. You Yo u are free to im implement plement any collect ion of your c hoic hoic e such as Map and Set.
12
Kotlin
In the following following example, example, we have implemente plemented d Map and Set using using different builtbuilt- in methods. fun main(args: main(args: A rray) rray) { val items = listOf(1, listOf(1, 2, 3, 4) println("First println("First Element of o ur list----"+items.first()) list----"+items.first()) println("First println("First Element of o ur list----"+items.last()) println("Even println("Even Numbers of our our List List ----"+items.filter ----"+items.filter { it % 2 == 0 }) returns [2, 4]
//
val readWriteMap readWriteMap = hashMapOf("foo" to 1, "bar" to 2) println(readWriteMap println(readWriteMap["foo"]) ["foo"])
// prints prints "1"
val strings = hashSetOf("a", hashSetOf("a", "b", "c", "c") println("My println("My Set Values are"+strings) are"+strings) }
The above piece of code yields the t he following following output in the browser.
Ranges Ranges is another unique unique c haract eristic of Kotlin. Kotlin. Like Haskell, Haskell, it provides provides an operator t hat hat helps you iterate iterat e through a range. range. Internally, Internally, it is implem impleme e nted using rangeTo() rangeTo() and its operator form is (..). (..).
13
Kotlin
In the following following example, example, we will will see how Kotlin Kotlin interpret interpret s t his range operator. fun main(args: main(args: A rray) rray) { val i:Int =2 for (j in 1..4) print(j) print(j) // prints "1234" if (i in 1..10) 1..10) { // equivalent of 1 <= i && i <= 10 println("we found your number --"+i) }
}
The above piec piec e of c ode yields yields the t he following following output in the browser.
14
5.
Kotlin - Control Flow
Kotlin
In the previous previous c hapter we have learned learned about diffe different rent ty pes of data ty pes available available in Kotlin syst em. em. In this chapt er, we will will disc uss different ty pes of control flow mec mec hanis m available in the Kotlin.
If - Else Kotlin is a functional language hence like every functional language in Kotlin “ if ” is an expression, expression, it is not a keyword. keyword. T he expression expression “if” will return a value whenever whenever nec essary . Like Like other ot her programming programming language, “if-else “if-else”” block is used as an initial initial c onditional c hecki hec king ng operator. In the following following example, example, we will compare compare t wo variables variables and provide provide t he require require d output acc ordin ordingl gly. y. fun main(args: main(args: Array) { val a:Int=5 val b:Int=2 var max: Int if (a > b) { max = a } else { max = b } print("Maximum of"+max)
// As expression // val max = if (a > b) a else b }
The above piec piec e of code c ode yields yields t he following following output as a result result in the browser. Our exampl exampl e also contains another lin line e of code, which depic depic ts how to use “I “ If ” statement as an expression.
15
Kotlin
Use of When If you are famili familiar ar with other program programming ming languages languages,, then you might might have heard of the term te rm switc h state st atem ment, ent , whic whic h is basically a conditional operator operat or when multiple ultiple c onditions can be applied on a particular variable. “when “when”” operator matches the variable value against the branch branch c onditions. If it it is satisfying satisfy ing the branch branch c ondition then it will will exec ute the stat ement ement inside that sc ope. In In the following following example, example, we will learn more about “when” in Kotlin. fun main(args: main(args: A rray) rray) { val x:Int=5 when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { // Note the block print("x is neither 1 nor 2") } } }
The above piec piece e of c ode yields yields the t he following following output in the browser.
16
Kotlin
In the above example, example, Kotlin c ompil ompiler er matc at c hes the value of x with the given branches. If it is is not matc matc hing hing any of t he bran branc c hes, t hen it it will execute the else part. part. Prac Prac tically, w hen is equivalent equivalent t o multiple ultiple if block. Kotlin provides provides another flexibil flexibility ity to the developer, where the developer c an provide provide multiple c hec ks in t he same line by providing providing “ ,” inside inside the c hecks. hec ks. Let us modify the above example example as follows. fun main(args: main(args: A rray) rray) { val x:Int=5 when (x) { 1,2 -> print(" Value of X either 1,2")
else -> { // Note the block print("x is neither 1 nor 2") } } }
Run the same same in the browser, browser, which will yield t he following following output in t he browser.
For Loop Loop is such an invention t hat provides provides the flexibil flexibility ity to iterate throu t hrough gh any kind of dat a struct st ruct ure. Like Like ot her programming programming languages, language s, Kotlin also provides provides many many kinds of Looping methodology, however, among them “For “ For”” is the most most succ essful one. The im imple ple menta t io n and use of For loop loop is conc eptually simil similar ar to Java for loop. loop. T he following following example example shows how we c an use the t he same same in real-life examples. examples. fun main(args: main(args: A rray) rray) { val items = listOf(1, listOf(1, 2, 3, 4) for (i in items) println("values println("values of the array"+i) }
In the above piece of code, we have declared one list named as “items” and using for loop we are are iterat ing thr t hrough ough that defined list list and a nd printing printing its value value in the browser. Following is the output.
17
Kotlin
Following Following is anot another her exam example ple of code , where we are using using som so me librar library y function func tion to ma ke our development work easier than ever before. fun main(args: main(args: A rray) rray) { val items = listOf(1, listOf(1, 22, 83, 4) for ((index, value) in items.withIndex()){ items.withIndex()){ println("the println("the element at $index $index is $value") } }
Once we com c ompil pile e and exec exec ute the t he above piece piec e of c ode in in our coding ground, ground, it will will yield y ield the following following output in the browser. browser.
While Loop and Do-While Do-While Loop While While and DoDo-Whil While e work exact ly in a simil similar ar way like like t hey do in in other programmi programmi ng languages. languages. The only only difference bet ween t hese two loops is, is, in case c ase of DoDo-whil while e loop the c ondition will will be test t ested ed at the end of the loop. The following example example shows t he usage usage of the While loop. loop.
18
Kotlin
fun main(args: main(args: A rray) rray) { var x:Int=0 println("Example of While Loop--") while(x<=10){ println(x) x++ }
}
The above piec piec e of c ode yields yields the t he following following output in the browser.
Kotlin also has another loop called Do-While loop, where the loop body will be executed once, once , only t hen the condition will will be c hecked. hec ked. The following following example example shows t he usage of the Do-while loop. loop. fun main(args: main(args: A rray) rray) { var x:Int=0 do{ x=x+10 println("I println("I a m inside Do block---"+x) }while(x<=50)
}
19
Kotlin
The above piece of c code ode yields the following following output in in the browser. browser. In the above code, co de, Kotlin c ompil ompiler er will execut e t he DO DO block, then t hen it it will go for condition c hecki hec king ng in in while block.
Use of Return, Break, Continue If you are are familiar familiar with wit h any programmi programming ng language, language , t hen you must must have ha ve an idea of different keywords that help help us implem implement ent good control c ontrol flow in the applic applic ation. at ion. Foll F ollowing owing are the different keywords that can be used to control the loops or any other types of contro cont roll flow. Return: Return: Return et urn is is a keyword keyword that ret returns urns some some value to the calling calling funct ion from the c alled alled funct ion. In In the following following example, example, we will will implem implement ent this scenari sce nario o using using our Kotlin Kotlin c oding ground. ground. fun main(args: main(args: A rray) rray) { var x:Int=10 println("The value of X is--"+doubleMe(x)) } fun doubleMe(x:Int):Int{ doubleMe(x:Int):Int{ return 2*x; }
In the above piec piec e of code, c ode, we are c alling alling another func tion and multiplyi multiplying ng the input input with w ith 2, and ret return urning ing the resultant value to the called funct ion that is our main main funct ion. Kotlin Kotlin defines the t he func func tion in in a different manner manner that we will look at in a subsequent c hapter. For now, it it is enough enough to understand understand that the above code will will generate t he following following output o utput in the browser.
20
Kotlin
Continue & Break: Break: Continu Cont inue e and break are the most most vital part of a logical logical problem. problem. The “break” “break” keyword t erminates erminates the c ontroller ontroller flow if some some c ondition has failed and “continue” does the opposite. opposite . All this operation happens with imm immediate ed iate visibility. visibility. Kotlin is smarte smarte r than other ot her progr programm amming ing languages, languages, wherein t he developer c an apply more more than one label as visibil visibility. ity. The following piec e of c ode shows how we are are implem impleme e nting this label in Kotlin. fun main(args: main(args: A rray) rray) {
println("Example of Break and Continue") Continue") myLabel@ for(x in 1..10){ 1..10){ // appling the custom label if(x==5){ println("I am inside if block with value"+x+"\n-- hence it will close close the operation") operation") break@myLabel break@myLabel //specifing //specifing the label }else{ println("I am inside else block with value"+x) value"+x) continue@myLabel } } }
The above piece of code yields the t he following following output in the browser.
21
Kotlin
As you can c an see, t he c ontroller c ontinues the loop, until and unless unless the value value of x is 5. Onc Onc e the value of x reaches 5, it it st arts executing the if block block and onc e the break break stat ement ement is reached, the t he entire c ontrol flow terminates terminates the program program execut ion.
22
6.
Kotlin - Class & Object
Kotlin
In this c hapter, we will will learn the basic basic s of Object -Oriented Programm Programming ing (OOP) using Kotlin. We will will learn about c lass and its objec objec t and how to play wit h that objec t. By By definition of OOP, OOP, a c lass is a bluepri blueprint nt of a runtim runtime e entit y and objec t is its its st ate at e , which includes bot h its its behavior and st ate. at e. In Kotli ot lin, n, c lass declar dec laration ation c onsists of a class header and a c lass body surrounded surrounded by c urly urly braces, simil similar ar to Java. Class Class m yClass yClass {// class H eader
// class Body }
Like Like Java, Kotlin Kotlin also allows allows t o create creat e several object objec t s of a c lass and you are free to include inc lude its class members embers and functions. func tions. We can c ontrol the visibili visibility ty of the class c lass membe rs variables using different keywords that we will learn in Chapter 10 – Visibility Control. In the following following example, example, we will will c reate one one c lass and its its object through whic h we will will ac c ess ess different data mem members bers of that c lass. class class myClass { // property (data member) private private v ar name: String = "Tutorials.point"
// member function fun printMe() printMe() { print("You are at the best Learning website website Named- "+name) } }
fun main(args: main(args: A rray) rray) {
val obj = myClass() // create obj object of myClass myClass class obj.printMe() }
The above piece of code will yield yield the following out put in the browser, where we are c alling alling printMe() of myClass using its own object.
23
Kotlin
Nested Class By definition, when a class has been created inside another class, then it is called as a nested class. In Kotlin, Kotlin, nested class is is by default default stat ic, hence hence,, it c an be be acc essed without without c reating any any object objec t of that c lass. In the following following example, example, we will will see how Kotlin Kotlin interprets our nested class. fun main(args: main(args: A rray) rray) { val demo = Outer.Nested().foo() Outer.Nested().foo() // caling nested class method print(demo)
} class class Outer {
class Nested Nested { fun foo() = "Welcome to The TutorialsPoin TutorialsPoin t.com" t.com"
} }
The above piece of code will will yield the following following output in the browser. browser.
24
Kotlin
Inner Class When a nest ed class is mark marked ed as a “inner” “inner” , then it will be called as an Inner class. An inner inner c lass c an be ac c essed by the t he data member ember of the outer class . In the foll f ollowing owing example, example, we will be acc ac c essing the dat a member ember of the outer class. class . fun main(args: main(args: A rray) rray) { val demo = Outer().Nested().foo() Outer().Nested().foo() // caling nested class method print(demo)
} class class Outer { private private v al welcomeMessage: welcomeMessage: String = "W elcome elcome to the TutorialsPoint.com" TutorialsPoint.com" inner class Nested { fun foo() = welcomeMessage welcomeMessage } }
The above piece of code will yield yield the following out put in the browser, where we are c alling alling the nest ed c lass using using the default construct co nstruct or provided provided by Kotlin Kotlin c ompil ompilers ers at the time time of compiling.
25
Kotlin
Anonymous Inner Class Anonymous Anonymous inner inner c lass is a prett y good good conce c oncept pt that makes makes the life life of a programm programmer er very easy. Whenever we are im impleme pleme nting an interfac interfac e , the conc ept of anonymous anonymous inner inner block comes comes into picture. The conc ept of c reating reating an object of interfac interfac e using using runtim runtime e object object reference is known known as anonymous anonymous c lass. In the following following example, example, we will creat e an interfac e and and we will creat e an object of that t hat interfac e using Anonymous Anonymous Inner Inner c lass lass mechanism. fun main(args: Array) Array) { var programmer :Human :Human = object:Human object:Human // creating an instance of the interface { override fun think(){ // overiding the think method print("I am an e xample xample of Anonymous Inner Class ") } }
programmer.think() } interface Human{ fun think() }
The above piece of code will will yield t he following following output in the browser. browser.
26
Kotlin
Type Aliases Type Ty pe aliases are a propert propert y of Kotli ot lin n c ompil ompiler. er. It provides provides the flexibi flexibili lity ty of creating c reating a new name name of an exist existing ing type, ty pe, it does not c reate a new type. t ype. If the t ype name name is t oo long, you c an easily introduce a shorte shorterr nam name e and use use the same same f or future usage. Type aliases aliases is really really helpful for complex complex type. ty pe. In the t he latest version, ve rsion, Kot Kotli lin n revoked the t he support for typ ty pe aliases, aliases, however, if you are using an old version of Kotlin Kotlin you may may have use it it like like the following typealias typealias NodeSet = Set Set
typealias typealias FileTable = MutableMap>
27
7.
Kotlin Kotli n - Con Constr structo uctors rs
Kotlin
In this chapter, chapt er, we will learn learn about c onstruct ors in Kotlin. Kotlin. Kotlin Kotlin has two types of constructor - one is the primary constructor constructor and the other is the secondary constructor. constructor. One Kotlin Kotlin c lass c an have one prim primary ary c onstructor onstruc tor,, and one or mo re sec ondary c onstruct or. Java const ruct or initializes initializes the member ember variables, variables, however, in Kotlin t he prim primary c onstructor onstruc tor initializes initializes the c lass, whereas whereas t he sec ondary c onstructor onstruc tor helps to inc inc lude some some extra logic logic while while initializi initializing ng the same. same. The prim primary c onstructor onstruc tor c an be dec lared lared at class header level as shown in the followi f ollowing ng example. example. class class Person(val firstName: String, var age: Int) { // class body }
In the above example, example, we have have dec lared lared t he prim primary c onstructor onstruc tor inside inside the parenthesis. parenthesis. Among Among the two fields, first name name is read- only as it is declared as “val” , while the field age c an be edited. In the following following example, example, we will use the prim primary c onstructor. onstruc tor. fun main(args: main(args: A rray) rray) {
val person1 = Person("TutorialsPoint.com", Person("TutorialsPoint.com", 15)
println("First println("First Name = ${person1.firstName}") ${person1.firstName}") println("Age println("Age = ${person1.age}") ${person1.age}") }
class class Person(val firstName: String, var age: Int) {
}
The above piec e of code will will autom auto matic ally ally initialize initialize the t wo variables variables and provide provide t he following output in the browser.
28
Kotlin
As mentioned mentioned earlier, earlier, Kotlin Kotlin allows to t o c reate one or more sec ondary c onstructor onstruc tors s for your class. This This secondary constructor is created usin using g the “c the “construct onstruct or” keyword. It is require require d whenever you want t o c reate more than one const ruct or in in Kot Kotli lin n or whenever you want to include more more logic logic in the prim primary ary c onstructor onstruc tor and you cannot do that because the prim primary c onstructor onstruc tor may be c alled alled by some some other ot her class. T ake a look at the following example, example, where we have created creat ed a secondary sec ondary construc tor and are using using the above example example t o imple implem ment t he same. fun main(args: main(args: A rray) rray) {
val HUman = HUman("TutorialsPoint.com", HUman("TutorialsPoint.com", 25)
print("${HUman.messa print("${HUman.message}"+"${HUman.f ge}"+"${HUman.firstName}"+"Wel irstName}"+"Welcome come to the e xample xample of Secondary Secondary constructor, constructor, Your Age is-$ {HUman.age}") {HUman.age}") }
class class HUman(val firstName: String, String, var age: Int ) { val message:String ="Hey!!!" constructor(name constructor(name : String , age :Int ,message :String):this(name,age){ :String):this(name,age){
} }
Note: Note : Any num number ber of sec ondary ondary c onstruc onstruc tors can be c reated, however, however, all of those c onstructors onstruc tors should c all the prim primary ary c onstruct or direc direc tly or indirect indirect ly.
29
Kotlin
The above piece of code will will yield t he following following output in the browser. browser.
30
8.
Kotlin - Inheritance
Kotlin
In this chapter, chapte r, we will will learn about inheri inherita tance nce.. By definition, definition, we all all know that inheri inherita tance nce means acc ac c ruing ruing some some properties properties of the mot mother her c lass into the t he c hild hild class. c lass. In Kotlin Kotlin,, the base class is named named as “Any”, whic whic h is the super class of the ‘ the ‘any any’ ’ default default class declared in Kotlin. Kotlin. Like Like all other OOPS, Kotlin also provides this func func tionality using one keyword known as “: “ :”. Everything in Kotlin Kotlin is by default default final, f inal, hence, henc e, we need to use the keyword “open” in front of the c lass declar dec laration ation t o make it allowable allowable to inheri inherit. t. T ake a look at the following following exampl example e of inheritance. import import java.util.Arrays java.util.Arrays
open open class ABC{ fun think (){ print("Hey!! print("Hey!! i am t hiking hiking ") } } class class B CD: ABC(){ // i nheritence nheritence happend using default constructor
}
fun main(args: main(args: A rray) rray) { var
a=BCD()
a.think() }
The above piece of code will will yield the following following output in the browser. browser.
31
Kotlin
Now, what if we want to override override the t hink() hink() method in the child child c lass. Then, we need to c onsider the following following example example where we are c reating two c lasses and override override one of its its function into into t he child c lass. import import java.util.Arrays java.util.Arrays
open open class ABC{ open open fun think (){ print("Hey!! print("Hey!! i am thinking ") } } class class B CD: ABC(){ // i nheritance nheritance happens using default constructor override override fun think(){ print("I print("I Am from Ch ild") } }
fun main(args: main(args: A rray) rray) { var
a=BCD()
a.think() }
32
Kotlin
The above piece of code will will c all the child class inheri inherite ted d method et hod and it will yield y ield the following output in the browser. Like Java, Kotlin too doesn’t allow multiple inheritances.
33
9.
Kotlin - Interface
Kotlin
In this chapter, we will learn learn about the interfac interfac e in Kotlin. Kotlin. In Kotlin, Kotlin, the inte interfac rface e works works exact ly simil similar ar to Java 8, which means they can contain cont ain method et hod implem implementat entat ion as well as abstract methods declaration. An interface can be implemented by a class in order to use its its defined funct f unct ionality. ionality. We have already introduc introduced ed an exam example ple with an interfac e in Chapter Chapter 6 - sect ion “anonym ion “anonymous ous inner class” . In this chapter, c hapter, we will will learn more more about it. The keyword “interface” is used to define an interface in Kotlin as shown in t he following following piece piece of code. interface interface ExampleInterface {
var myVar: String
// abstract property
fun absMethod() absMethod()
// abstract method method
fun sayHello() sayHello() = "Hello there" // method with default implementation implementation }
In the above example, we have have c reated one interfac e named named as “ExampleIn “ExampleInte terfac rface” e” and inside inside that we have have a couple c ouple of abstract abst ract properties properties and met methods hods all toget her. Look Look at the funct ion named “sayHello()” “sayHello()” , which w hich is an implem impleme e nted nte d method. et hod. In the following following example, example, we will will be implem impleme e nting
interface interface ExampleInterface ExampleInterface
var myVar: Int
the above interface inte rface in in a c lass.
{
// abstract property
fun absMethod():String absMethod():String
// abstract method
fun hello() { println("Hello println("Hello there, Welcome to Tu torialsPoint.Com!") torialsPoint.Com!") } }
class class InterfaceImp : E xampleInterface xampleInterface {
override override var myVar: Int = 25 override override fun absMethod() = "Happy Learning " 34
Kotlin
}
fun main(args: main(args: A rray) rray) { val obj = InterfaceImp()
println("My println("My Variable Value is = ${obj.myVar}") print("Calling hello(): ")
obj.hello()
print("Message print("Message from the Website-Website-- ") println(obj.absMethod()) }
The above piece of code will will yield t he following following output in the browser browser .
As mentioned earlier, Kotlin doesn’t support multipl multiple e inheri inherita tance nce s, however, the t he same thing c an be ac hieved by im impleme pleme nting more than two t wo interfac es at a time. time. In the following following example, example, we will creat e two tw o interfac es and late laterr we will implement plement both the interface interface s into a c lass. interface A {
fun printMe() printMe() { println(" method method of interface A") } }
35
Kotlin
interface B
{
fun printMeToo() printMeToo() { println("I am another Method Method from interface B") } }
// implements implements two interfaces A and B class class m ultipleInterfaceExam ultipleInterfaceExample: ple: A, B
fun main(args: main(args: A rray) rray) { val obj = multipleInterfaceExample( multipleInterfaceExample() )
obj.printMe() obj.printMeToo() }
In the above exam example, ple, we have create d two sample sample interfac es A, B and and in the class named “multipl “multipleInterfac eInterfac eExample” we have implem impleme e nted two tw o interfac e s declar dec lared ed earlier. earlier. The above piece of c ode will yield t he following following output in t he browser.
36
10.. 10
Kotlin - Vis Visibili ibility ty Co Control ntrol
Kotlin
In this chapte r, we will learn about different modifiers modifiers available available in Kot Kotli lin n language. language. Access modifier is used to rest restri ric c t the usage of the t he variables, variables, methods and class used in in the applic applic ation. at ion. Like Like other ot her OOP programm programming ing language, language, this modifier modifier is applic applic able at multip multip le places suc h as in the c lass header or met method hod declar dec laration. ation. There are four acc ess modifier s available in Kotlin.
Private The classes, met methods, hods, and packages can be declar dec lared ed with a privat private e modifier modifier.. Once anything is dec lared lared as private private , then t hen it will will be ac c essible within its immediate ed iate scope. sc ope. For instance, a private package can be accessible within that specific file. A private class or interfac interfac e can be acc essible essible only only by its data mem member bers, s, etc . private private class privateExample { private private val i = 1
private private v al doSomething() doSomething() { } }
In the above example, the class “privateExample “ privateExample”” and the variable variable i both can be acc ac c essible only in the same same Kotli ot lin n fil f ile, e, where it s mentioned mentioned as they all all are declared as private in the declaration block.
Protected Protec ted te d is anot another her acc ess modifier for Kotlin, w hich is is currently not available available for top level level declaration declaration like like any package package cannot be protec protec ted. A protec protec ted class or interface is visible visible to its subclass only. only. class class A { protected protected val i = 1 } class class B : A() { fun getValue() getValue() : Int { return i } }
37
Kotlin
In t he above example, example, the variable “i “ i” is declared as protected, protected , hence, hence , it it is only only visible visible to its subclass.
Internal Internal Inte rnal is a newly added modifier modifier introduc ed in Kot Kotlin. lin. If anyt hing is marked marked as a s inte internal, rnal, then that specific field will be in the inte internal rnal field. An A n Internal pac kage is visible visible only inside the module module under which it is implem implemente ented. d. An internal c lass interfac e is is visible visible only by other class present present inside inside t he same same pac kage or the module. module. In the following example, example, we will see how to im implement plement an internal internal method. et hod. class class internalExample { internal val i = 1
internal internal fun doSomething() { } }
In the above example, the met method hod named named “doSomet “doSomethin hing” g” and t he variable variable is mention mentione ed as internal, hence, hence , these two fields c an be acc essible only only inside inside the t he package under which it is declared.
Public Public Public modifier is acc ac c essible from anywhere in the project project wo rkspac rkspace. e. If no acc ess modifie r is specified, t hen by default it will will be in in t he public public scope. sc ope. In all our previous previous examples, examples, we have not mentioned mentioned any modifier, modifier, hence , all of them are are in t he publi public c scope. sc ope. Following Following is an exam example ple to understand understand more on how to dec lare lare a public public variable variable or met method. hod. class class publicExample { val i = 1
fun doSomething() doSomething() { } }
In the above above example, example, we have not mentioned mentioned any modifier, modifier, thus all all these met methods hods and variables are by default public.
38
11. Kotlin - Extension
Kotlin
In this chapter, c hapter, we will will learn about another new feat ure of Kotlin Kotlin named named “Extension”. Using extension, we will will be able to add or remove remove some some method et hod f unct ionality ionality even e ven without without inheriting inheriting or modifying modifying them. Exte Extensions nsions are resolved resolved statist st atist ically. It does not actually ac tually modify odify the existing existing class, but it c reates a c allabl allable e funct ion that c an be c alled alled with a dot operation.
Function Extension In function func tion extension, Kotlin Kotlin allows allows to define a met method hod outside of the main main c lass. In the following following example, example, we will will see how the extension is implem implemente ented d at the funct ional level. class class Alien{ var skills skills : String= "null" fun printMySkills(){ printMySkills(){ print(skills) } } fun main(args: main(args: A rray) rray) { var
a1= Alien()
a1.skills="JAVA" //a1.printMySkills()
var
a2= Alien()
a2.skills="SQL" //a2.printMySkills()
var
a3= Alien()
a3.skills=a1.addMySkills(a2) a3.printMySkills() }
39
Kotlin
fun Alien.addMySkills(a: Alien.addMySkills(a:Alien):String{ Alien):String{ var a4=Alien() a4=Alien() a4.skills=this.ski a4.skills=this.skills lls + " " +a.skills +a.skills return a4.skills }
In the above example, we don’t have any method inside “Alien” class named as “addMySkill “addMySkills()” s()” , however, w e stil st illl are implem impleme e nting the same same method et hod somewhere somewhere else outside of the class, This is the magic of extension. The above piece of code will will generate the following following output in the browser. browser.
Object Extension Kotlin provides another mec mechani hanism sm to implem implement ent static sta tic funct ionality ionality of Java. This c an be achieved using the keyword “companion “companion object ”. Using this mechanism, mechanism, we can c reate an object of a c lass inside inside a fac tory method et hod and lat later er we c an just call c all that met method hod using the reference of the class name. name. In the following following exam e xample, ple, we will c reate a “com “c ompanio panio n object” . fun main(args: main(args: A rray) rray) { println("Heyyy!!!"+A.show()) }
class A{ companion companion object{ fun show():String{ return("You are learning Kotlin from TutorialsPoint.com") TutorialsPoint.com") } } }
40
Kotlin
The above piece of code will will yield t he following following output in the browser. browser.
The above example example seems seems like like stat s tat ic in Java, however, in real-tim real-t ime e we are creating c reating an object as a mem member ber variable variable of that same same c lass. This is why it is also included unde r extension property and can be alternatively called as an object extension. You are basically extending t he object of t he same same c lass to use some some of t he member ember functions func tions .
41
12. Kotlin - Data Classes
Kotlin
In this chapter, chapt er, we will learn more more about Dat Data a c lasses of Kotlin Kotlin programm programming ing language language . A c lass c an be mark marked ed as a Data Data c lass whenever it is mark marked ed as ”data”. This t ype of class can be used to hold hold the basic basic data apart apart . Other than t his, his, it does not provide provide any other functionality. All the data dat a c lasses need to have one prim primary c onstructor onstruc tor and all the prim primary ary c onstruct or should should have at least least one paramet parameter. er. Whenever a class is is mark marked ed as data , we can c an use some of t he inbui inbuilt lt funct ion of of t hat data c lass such such as “toSt ring()”,”hasCode()” ring()”,”hasCode()” , etc . An Any y data c lass c annot have a modifier modifier like like abstract abst ract and open or internal. Data c lass can be extended to other classes too. In In tthe he following following example, example, we will will c reate one dat a c lass. fun main(args: main(args: A rray) rray) { val book: Book = Book("Kotlin", Book("Kotlin", "TutorialPoint.com", "TutorialPoint.com", 5) println("Name println("Name of the Book is--"+book.name) is--"+book.name) // "Kotlin" println("Puclisher println("Puclisher Name- -"+book.publisher) -"+book.publisher) // "TutorialPoint.com" "TutorialPoint.com" println("Review println("Review of the b ook is--"+book.reviewScore) is--"+book.reviewScore) // 5 book.reviewScore book.reviewScore = 7 println("Printing println("Printing all th e info al l together--"+book.toString()) together--"+book.toString()) //using inbuilt inbuilt function of the d ata class println("Example println("Example of t he HasCode function-- "+book.hashCode()) "+book.hashCode())
}
data data class Book(val name: String, val publisher: String, String, var reviewScore: reviewScore: Int)
The above piece of code will yield the following output in the browser, where we have created one data class to hold some of the data, and from the main function we have acc ac c essed all all of its data mem members. bers.
42
13. Kotlin - Sealed Class
Kotlin
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 t ype of a predefined predefined type. ty pe. To make make a sealed c lass, we need to use the keyword “sealed” as a modifier modifier of that c lass. A sealed c lass c an have its own sub class but all those subclasses need t o be dec lared lared inside t he same same Kotlin file along with t he sealed c lass. In the following following example, example, we will will see how to use a sealed c lass. sealed class MyExample { class OP1 : MyExample() // MyExmaple MyExmaple class can be of two types only class OP2 : MyExample() } fun main(args: main(args: A rray) rray) { val obj: MyExample = MyExample.OP2() MyExample.OP2() val output = when (obj) { // defining the object of the class depending on the inuputs is MyExample.OP1 MyExample.OP1 -> " Option Option One has been chosen" chosen" is MyExample.OP2 MyExample.OP2 -> " option Two has been chosen" chosen" } println(output) }
In the above example, we have one sealed c lass named named “MyExample” “MyExample” , which which c an be of two types only only - one is is “OP1” and another one is “OP2”. “OP2”. In the main main c lass, lass , we are c reating reating an object in our class and assigning assigning its type at runtime. runtime. Now, as t his “MyExample” “MyExample” c lass is sealed, we can apply t he “when ” clause at runtim runtime e to impleme pleme nt the final output. In sealed class, we need not use any unnece unnecessary ssary “else” stat ement ement to com c omplex plex out the c ode. The above piece piec e of code will will yield the following following output in t he browser.
43
14.. 14
Kotlin - Generics
Kotlin
Like Like Java, Ja va, Kot Kotlin lin provides provides higher order of variable t yping called as Generic Generics. s. In this c hapter, we will will learn how Kot Kotli lin n implem implement ents s Generics Generics and how as a developer we can use those funct ionalities ionalities provided provided inside inside t he generic generic s librar library. y. Implem Impleme e ntat ion wise, wise , generic generic s is prett y simil similar ar to Java but Kotlin Kotlin developer has introduced two new keywords “out “ out”” and “in “in”” t o make Kotli ot lin n c odes more readable readable and easy for t he developer. In Kot Kotli lin, n, a c lass and a type are are totally to tally different c oncept once pt s. As per t he example, example, List is a c lass in Kotlin, whereas List< List is a type in Kot Kotlin. lin. The following exam e xample ple depic ts how generics generic s is imple implem mented ent ed in Kot Kotlin. lin. fun main(args: main(args: A rray) rray) { 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 t o a number number variable. This is is possible bec be c ause “Int” “Int” is a subclass subclass of Num Number ber c lass, lass , hence the type conversion happens happens aut omatic omatic ally at runtim runtime e and produce produce s the output output as “1” . Let us learn learn somet somethin hing g more about generics generics in Kot Kotli lin. n. It is bett er to go for generic generic dat a type whenever we are not sure about the data type we are going to use in the application. Generally, Generally, in Kotlin generics ge nerics is defined def ined by where “T” stands for template , which can be determ det ermined ined dynamic dynamic ally by Kotlin c omplier. omplier. In t he following exam e xample, ple, we will see how to use generic generic data types in in Kotlin programmi programming ng language language.. fun main(args: main(args: A rray) rray) { var objet=genericsExample( objet=genericsExample("JAVA") "JAVA") var o bjet1=genericsExampl bjet1=genericsExample(10) e(10) }
class class genericsExample(input:T){ genericsExample(input:T){ init{ println( "I am getting called with the value "+input) } }
44
Kotlin
In the above piece of code, we are creating one class with generic return type, which is represented as . Take Ta ke a look look at the main main method, et hod, where we have dynam dynamically ically defined its value at the run by provin proving g the value type , while while creating the object object of t his his c lass. This is how how generic generic s is interpreted interpreted by Kotlin Kotlin c ompil ompiler. er. We will get the following following output in the browser, once we run this code in our coding ground.
When we want to assign the generic type to any of its super type, then we need to use “out” keyword, keyword, and when we want to assign assign t he generi generic c type to any any of its its sub- type, then we need to use “in” keyword. In the following example, we will use “out” keyword . Similarl Similarly, y, you can t ry using using “in” keyword. fun main(args: main(args: A rray) rray) { var o bjet1=genericsExampl bjet1=genericsExample(10) e(10) var o bject2=genericsExamp bject2=genericsExample(10.00) le(10.00) println(objet1) println(object2) }
class class g enericsExample(input:T){ init{ println( "I am getting called with the value "+input) } }
The above code c ode will yield t he following following output in the browser. browser.
45
15.. 15
Kotlin - De Deleg legation ation
Kotlin
Kotlin supports “delegation” supports “delegation” design pat tern te rn by introducing a new keyword “by”. by ”. Using this keyword or delegation met methodology, hodology, Kotlin Kotlin allows the derived derived c lass to acc ess all the implem implemente ented d public public met methods hods of an inte interfac rface e through a spec ific objec objec t . The following example example demonstrat es how t his happens in Kot Kotlin. lin. interface interface Base { fun printMe() printMe() //abstract method }
class class BaseImpl(val x: Int) : Base { override override fun fun printMe() { println(x) }
//implementation //implementation of the method
}
class class Derived(b: Base) Base) : Base by b object b
// delegating the the public method method on the
fun main(args: main(args: A rray) rray) { val b = BaseImpl(10) Derived(b).printMe() // prints 10 :: accessing the printMe() method }
In t he example, example, we have one interfac e “Base” “Base” with w ith its abstract met method hod named named “printm “printme() e() ”. In t he BaseImpl BaseImpl c lass, we are implem impleme e nting nt ing t his “printme()” “printme()” and later late r from another class we are using this implementation using “by” keyword. keyword . The above piece of code will will yield t he following following output in the browser. browser.
46
Kotlin
Property Delegation In the previous previous sec tion, we have learned learned about the delegation design pattern using “by” keyword. In this sec t ion, we will learn learn about delegation of properties properties using using som so me standard st andard methods mentioned in Kotlin library. Delegation means passing the responsibil responsibility ity to another class c lass or method. et hod. When a property property is already already declar dec lared ed in some some places , then we should should reuse the same same c ode to initialize initialize them. In the following following examples, examples, we will will use some some standard st andard delegation methodology et hodology provide provide d by Kotlin and a nd some standard standa rd library library func t ion while imple implem menting ent ing delegat ion in our examples.
Using Lazy() Lazy is a lam lambda bda funct ion which t akes a property property as an input input and in ret return urn gives an an instanc instanc e of Lazy, Lazy, where is basic basic ally ally the type of the properties it is using. Let us take a look at the following following to underst understand and how it works. works. val myVar: myVar: String by lazy {
"Hello" }
fun main(args: main(args: A rray) rray) { println(myVar println(myVar +" My d ear friend")
}
In the above piece of c ode, we are passing a variable “myVar” “myVar” t o the Lazy funct ion, ion, which in return assigns t he value to its its object o bject and returns the same same to the main main function. func tion. Following Following is the t he output output in t he browser.
47
Kotlin
Delegetion.Observable() Observable() Observable() takes two t wo argum argument s to initiali initialize ze the objec t and returns t he same same t o the c alled alled func tion. In the following following example, example, we will will see s ee how to use Observable() method et hod in order to implem implement ent delegation. import import kotlin.properties.Deleg kotlin.properties.Delegates ates
class class User { var name: String by D elegates.observable( elegates.observable("Welcome "Welcome to T utorialspoint.com") utorialspoint.com") { prop, old, new -> println("$old -> $new") } }
fun main(args: main(args: A rray) rray) { val user = User() User() user.name user.name = "first" user.name user.name = "second" }
The above piece of code will will yield t he following following output in the browser. browser.
In general, the synt ax is is the expression aft a fter er the “by” keyword is delegated. The get() and set() methods set() methods of the variable p will be delegated to its getValue() getValue() and setValue() methods defined in the Delegate class. class class Example { var p: String by Delegate() Delegate() }
48
Kotlin
For the above piec piece e of c ode, followin following g is the delegate delegate class t hat we need t o generate generate in order to assign the value in the variable p. class class Delegate { operator operator fun getValue(thisRef: getValue(thisRef: Any?, property: KProperty<*>): KProperty<*>): String { return "$thisRef, "$thisRef, thank you for delegating '${property.name}' '${property.name}' to me!" }
operator operator fun setValue(this setValue(thisRef: Ref: An y?, property: KProperty<*>, value: String) { println("$value println("$value has been assigned to '${property.name} '${property.name} in $thisRef.'") } }
While While reading, reading, getValue() get Value() met method hod will be c alled alled and while while sett ing the variable variable setValue() set Value() method will be called.
49
16.. 16
Kotlin Kotli n - Functions Functions
Kotlin
Kotlin is a static sta tic ally ally typed language, language, hence , func func t ions play a great great role role in it. We are pret pretty ty famil familiar iar with funct ion, as we are using f unct ion throughout the examples. examples. Funct ion is declar dec lared ed with wit h the keyword “fun”. Like any other OOP, OOP , it also needs a return type and an option argument list. In the following following example, example, we are are definin de fining g a funct ion c alled alled MyFunction MyFunc tion and from the ma ma in function we are calling this function and passing some argument. fun main(args: main(args: A rray) rray) {
println(MyFunction("tutorialsPoint.com")) } fun MyFunction(x: MyFunction(x: String): String { var c:String c:String ="Hey!! Welcome To - --" return return (c +x) }
The above piece of code will will yield t he following following output in the browser. browser.
The funct ion should be dec lared lared as follows fun ((::): ntType>):
Following are some of the different types of function available in Kotlin.
50
Kotlin
Lambda Function Lambda Lambda is a high level funct f unct ion that drastically drastic ally reduces t he boiler boiler plate c ode while while dec de c laring laring a funct ion and defining defining t he same. same. Kotlin Kotlin allows you to define define your yo ur own lam lambda. bda. In Kotlin Kotlin , you can declare your lam lambda bda and pass that lam lambda bda to a funct ion. Take a look at the t he following following example. example. fun main(args: main(args: A rray) rray) { val mylambda :(String)->Unit ={s:String->print(s)} ={s:String->print(s)} val v:String="TutorialsPoint. v:String="TutorialsPoint.com" com" mylambda(v) }
In the above code, we have created c reated our our own lambda lambda known known as “mylam “mylambda” bda” and we have passed one variable t o this lambda, lambda, which is is of type ty pe String String and c ontains a value value “Tut orialsPoin orialsPoint. t.c c om” om” . The above piece of code will will yield the following following output in the browser. browser.
Inline Function The above example example shows the basic of the lambda expression expression that we can use in Kotlin applic applic ation. at ion. Now, we c an pass a lam lambda bda to anot her funct ion to get our output which make make s the calling function an inline function. Take a look at the t he following following example. example. fun main(args: main(args: A rray) rray) { val mylambda:(String) mylambda:(String) ->Unit ->Unit ={s:String->print(s)} ={s:String->print(s)} val v:String="TutorialsPoint. v:String="TutorialsPoint.com" com" myFun(v,mylambda) / /passing lambda as a parameter of another function
}
fun myFun(a :String, action: (String)->Unit){ //passing lambda 51
Kotlin
print("Heyyy!!!") action(a)// action(a)// call to lambda function }
The above piece piece of code will will yield t he following following output in the browser. browser. Using inline inline funct ion, we have passed a lambda lambda as a param paramet eter. er. Any other function func tion can c an be made made an inline inline function using the “inl the “inline” ine” keyword. keyword.
52
17.
Kotlin - Destructuring Declarations
Kotlin
Kotlin c ontains many feat ures of other program programming ming languages. languages. It allows allows you to t o declar dec lare e multiple ultiple variables variables at once. onc e. This tec te c hnique hnique is is c alled alled Dest Dest ruc ruc turing dec laration. laration. Following Following is the basic syntax synta x of the destructuring destruc turing declaration. val (name, (name, age) = p erson
In the above syntax, we w e have created c reated an object and defined all of t hem toget her in a single statement. Later, we can use them as follows. println(name) println(age)
Now, let us see how we c an use the same same in our realreal- life life applic applic ation. Consider t he following example example where we are creating c reating one Student c lass with some some att ributes ributes and lat later er w e will will be using using t hem to print print t he object values. fun main(args: main(args: A rray) rray) { val s=Student("TutorialsPoint s=Student("TutorialsPoint.com","Kotlin") .com","Kotlin") val (name,subject)=s (name,subject)=s println("You println("You are learning "+subject+" from "+name) }
data data class Student( val a :String,val b: St ring ){ var name:String=a var subject:String=b }
The above piece of code will will yield t he following following output in t he browser.
53
18. Kotlin - Exception Handling
Kotlin
Exc Exc eption ept ion handling handling is a very im important part of a program programm ming language. language. This tec hnique hnique restrict s our applicat applicat ion from generat generating ing the t he wrong wrong output out put at runtim runtime. e. In this chapt er, we will learn learn how to handle handle runtim runtime e except ion in Kotlin. Kotlin. The except ions in in Kotlin is pretty simil similar ar to the except ions in in Java. All All the exc exc eptions ept ions are are desc des c endants of the “Throwable” c lass. Following Following example example shows how to use except ion handling handling tec te c hnique hnique in in Kot Kotli lin. n.
fun main(args: main(args: A rray) rray) { try{ val myVar:Int=12 val v:String="Tutorialspoint.com" v:String="Tutorialspoint.com" v.toInt() }catch(e:Exception){ e.printStackTrace() }finally{ println("Exception 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 ac tually a runtim runtime e except ion. Henc Hence, e, we will will get t he following following output in the browser.
Note: Note : Like Like Java, Kot Kotli lin n also execut es the finally finally block after executing execut ing the c atc h block.
54