KOTLIN: Quick Guide

From OnnoWiki
Jump to navigation Jump to search

Sumber: https://www.tutorialspoint.com/kotlin/kotlin_quick_guide.htm

Kotlin adalah bahasa pemrograman open source baru seperti Java, JavaScript, dll. Kotlin adalah bahasa tingkat tinggi yang diketik secara statis yang menggabungkan bagian fungsional dan teknis di tempat yang sama. Saat ini, Kotlin menargetkan Java dan JavaScript. Kotlin berjalan di JVM.

Kotlin dipengaruhi oleh bahasa pemrograman lain seperti Java, Scala, Groovy, Gosu, dll. Sintaks Kotlin mungkin tidak persis sama dengan JAVA, namun, secara internal Kotlin bergantung pada library Java Class yang ada untuk menghasilkan hasil yang luar biasa bagi para programmer . Kotlin memberikan interoperabilitas, keamanan, dan kejelasan kepada developer di seluruh dunia.

Keuntungan dan Kerugian

Berikut adalah beberapa keuntungan menggunakan Kotlin untuk pengembangan aplikasi Anda.

  • Easy Language − Kotlin adalah bahasa fungsional dan sangat mudah dipelajari. Sintaksnya sangat mirip dengan Java, sehingga sangat mudah diingat. Kotlin lebih ekspresif, yang membuat kode kita lebih mudah dibaca dan dimengerti.
  • Concise − Kotlin didasarkan pada JVM dan merupakan bahasa fungsional. Dengan demikian, ini mengurangi banyak code panjang yang digunakan dalam bahasa pemrograman lain.
  • Runtime and Performance − Performa lebih baik dan runtime pendek / singkat.
  • Interoperability − Kotlin cukup matang untuk membangun aplikasi yang dapat dioperasikan dengan cara yang tidak terlalu rumit.
  • Brand New − Kotlin adalah bahasa baru yang memberikan awal yang baru bagi pengembang. Ini bukan pengganti Java, meskipun dikembangkan melalui JVM. Ini diterima sebagai bahasa resmi pertama pengembangan android. Kotlin dapat didefinisikan sebagai - Kotlin = JAVA + tambahan fitur baru yang diperbarui.

Berikut ini adalah beberapa kelemahan dari Kotlin.

  • Namespace declaration − Kotlin memungkinkan pengembang untuk mendeklarasikan fungsi di tingkat atas. Namun, setiap kali fungsi yang sama dideklarasikan di banyak tempat aplikasi kita, maka akan sulit untuk memahami fungsi mana yang dipanggil.
  • No Static Declaration − Kotlin tidak memiliki static handling modifier seperti Java, yang dapat menyebabkan beberapa masalah bagi pengembang Java konvensional.

Kotlin - Setup Environment

Namun, jika kita masih ingin menggunakan Kotlin secara offline di sistem secara lokal, maka kita perlu menjalankan langkah-langkah berikut untuk mengonfigurasi local workspace.


Step 1 − Instalasi Java 8.

Kotlin run di JVM, karenanya. sangat penting untuk menggunakan JDK 8 untuk development Kotlin secara lokal. Silakan merujuk ke situs web resmi oracle untuk mengunduh dan menginstal JDK 8 atau versi di atasnya. Kita mungkin harus mengatur variabel environment untuk JAVA sehingga dapat bekerja dengan baik. Untuk memverifikasi instalasi kita di sistem operasi, ketik "java -version" di command prompt dan sebagai output itu akan menunjukkan versi java yang diinstal di sistem operasi tersebut.


Step 2 − instalasi IDE.

Ada sejumlah IDE yang tersedia melalui internet. Kita dapat menggunakan salah satu pilihan berikut. Kita dapat menemukan tautan unduhan IDE yang berbeda di tabel berikut.

IDE Name	Link Download
NetBeans	https://netbeans.org/downloads/
Eclipse	https://www.eclipse.org/downloads/
Intellij	https://www.jetbrains.com/idea/download/#section = windows

Selalu disarankan untuk menggunakan versi perangkat lunak terbaru untuk memperoleh hasil

maksimum dari IDE.


Step 3 − Configuring Eclipse.

Buka Eclipse dan masuk ke "Eclipse Market Place". Kita akan menemukan layar berikut.

Eclipse market place.png

Cari Kotlin di kotak search dan instal yang sama di sistem lokal. Mungkin butuh beberapa waktu tergantung pada kecepatan internet. Kita mungkin harus me-restart Eclipse, setelah berhasil diinstal.

Step 4 − Kotlin Project.

Setelah Eclipse berhasil dimulai ulang dan Kotlin diinstal, Anda akan dapat membuat proyek Kotlin dengan cepat. Buka File → New → Others dan pilih “Kotlin project” dari daftar.

Center

Kotlin project

Setelah penyiapan proyek selesai, kita dapat membuat file Kotlin di bawah folder “SRC”. Klik kiri pada folder "Src" dan tekan "new". Kita akan mendapatkan opsi untuk file Kotlin, jika tidak, Anda mungkin harus mencari dari "others". Setelah file baru dibuat, direktori proyek Anda akan terlihat seperti berikut.

Hello.png

Development environment sudah siap sekarang. Silakan dan tambahkan potongan kode berikut di file "Hello.kt".

fun main(args: Array<String>) {
   println("Hello, World!")
}

Run sebagai aplikasi Kotlin dan lihat output di konsol seperti yang ditunjukkan pada tangkapan layar berikut. Untuk pemahaman dan ketersediaan yang lebih baik, kita akan menggunakan tool dasar pengkodean ini.

Hello, World!

Kotlin - Arsitektur

Kotlin adalah bahasa pemrograman dan memiliki arsitektur sendiri untuk mengalokasikan memori dan menghasilkan output yang berkualitas kepada end user. Berikut ini adalah skenario yang berbeda di mana kompiler Kotlin akan bekerja secara berbeda, setiap kali ia menargetkan berbagai jenis bahasa lain seperti Java dan JavaScript.

Kompiler Kotlin membuat byte code yang mana byte code tersebut dapat berjalan di JVM, yang sama persis dengan byte code yang dihasilkan oleh file Java .class. Setiap kali file dengan byte code yang di hasilkan dari java dan kotlin run di JVM, mereka dapat berkomunikasi satu sama lain dan beginilah cara fitur interoperable dibuat di Kotlin untuk Java.

Architecture-kotlin.png

Setiap kali Kotlin menargetkan JavaScript, kompiler Kotlin mengonversi file .kt menjadi ES5.1 dan menghasilkan kode yang kompatibel untuk JavaScript. Kompiler Kotlin mampu membuat kode yang kompatibel dengan basis platform melalui LLVM.


Kotlin - Basic Data Type

Pada bagian ini, kita akan belajar tentang basic data type yang tersedia di Kotlin programming language.

Number

Representasi angka di Kotlin sangat mirip dengan Java, namun, Kotlin tidak mengizinkan konversi internal dari tipe data yang berbeda. Tabel berikut mencantumkan panjang variabel yang berbeda untuk tipe yang berbeda.

Type	Size
Double	64
Float	32
Long	64
Int	32
Short	16
Byte	8

Dalam contoh berikut, kita akan melihat bagaimana Kotlin bekerja dengan tipe data yang berbeda. Silakan masukkan dan jalankan code berikut.


fun main(args: Array<String>) {
   val a: Int = 10000
   val d: Double = 100.00
   val f: Float = 100.00f
   val l: Long = 1000000004
   val s: Short = 10
   val b: Byte = 1
   
   println("Your Int Value is "+a);
   println("Your Double  Value is "+d);
   println("Your Float Value is "+f);
   println("Your Long Value is "+l);
   println("Your Short Value is "+s);
   println("Your Byte Value is "+b);
}

Ketika kita menjalankan potongan code di atas, maka output berikut akan tampil di console.

Your Int Value is 10000
Your Double Value is 100.0
Your Float Value is 100.0
Your Long Value is 1000000004
Your Short Value is 10
Your Byte Value is 1

Character

Kotlin mewakili karakter menggunakan char. Karakter harus dideklarasikan dalam tanda kutip tunggal seperti 'c'. Silakan masukkan kode berikut dan lihat bagaimana Kotlin menginterpretasikan variabel karakter. Variabel karakter tidak dapat dideklarasikan seperti variabel angka. Variabel Kotlin dapat dideklarasikan dengan dua cara - yaitu menggunakan "var" dan menggunakan "val".

fun main(args: Array<String>) {
   val letter: Char    // defining a variable 
   letter = 'A'        // Assigning a value to it 
   println("$letter")
}

Potongan code di atas akan menghasilkan output berikut di console output.

A

Boolean

Boolean sangat sederhana seperti bahasa pemrograman lainnya. Kita hanya memiliki dua nilai untuk Boolean – benar atau salah. Dalam contoh berikut, kita akan melihat bagaimana Kotlin menginterpretasikan Boolean.


fun main(args: Array<String>) {
   val letter: Boolean   // defining a variable 
   letter = true         // Assinging a value to it 
   println("Your character value is "+"$letter")
}

Potongan code di atas akan menghasilkan output berikut.

Your character value is true

String

String adalah array karakter. Seperti Java, String tidak dapat diubah sifatnya. Kita memiliki dua jenis string yang tersedia di Kotlin - satu disebut raw String dan yang lainnya disebut escaped String. Dalam contoh berikut, kita akan menggunakan string ini.

fun main(args: Array<String>) {
   var rawString :String  = "I am Raw String!"
   val escapedString : String  = "I am escaped String!\n"
   
   println("Hello!"+escapedString)
   println("Hey!!"+rawString)   
}

The above example of escaped String allows to provide extra line space after the first print statement. Following will be the output in the browser.

Contoh escaped String di atas memungkinkan untuk memberikan ruang baris tambahan setelah pernyataan cetak pertama. Berikut adalah output yang dihasilkan.

Hello!I am escaped String!
Hey!!I am Raw String!

Array

Array adalah kumpulan data yang homogen. Seperti Java, Kotlin mendukung array dari tipe data yang berbeda. Dalam contoh berikut, kita akan menggunakan array yang berbeda.

fun main(args: Array<String>) {
   val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
   println("Hey!! I am array Example"+numbers[2])
}

Potongan code di atas menghasilkan output berikut. Pengindeksan array mirip dengan bahasa pemrograman lain. Di sini, kami mencari indeks kedua, yang nilainya "3".

Hey!! I am array Example3

Collection

Collection adalah bagian yang sangat penting dari struktur data, yang membuat pengembangan perangkat lunak menjadi mudah bagi para engineer. Kotlin memiliki dua jenis collection, yaitu:

  • immutable collection (seperti list, map, dan set yang tidak dapat diedit)
  • mutable collection (jenis collection ini dapat diedit).

Sangat penting untuk mengingat jenis collection yang digunakan dalam aplikasi kita, karena sistem Kotlin tidak mewakili perbedaan spesifik apa pun di dalamnya.

fun main(args: Array<String>) { 
   val numbers: MutableList<Int> = mutableListOf(1, 2, 3) //mutable List 
   val readOnlyView: List<Int> = numbers                  // immutable list 
   println("my mutable list--"+numbers)        // prints "[1, 2, 3]" 
   numbers.add(4) 
   println("my mutable list after addition --"+numbers)        // prints "[1, 2, 3, 4]" 
   println(readOnlyView)     
   readOnlyView.clear()    // ⇒ does not compile  
// gives error  
}

Potongan code di atas akan menghasilkan output berikut. Kotlin memberikan error ketika kita mencoba menghapus daftar mutable collection yang bisa berubah.

main.kt:9:18: error: unresolved reference: clear
readOnlyView.clear() // -> does not compile
^

Dalam collection, Kotlin menyediakan beberapa method yang berguna seperti first(), last(), filter(), dll. Semua method ini bersifat self-descriptive dan mudah diimplementasikan. Selain itu, Kotlin mengikuti struktur yang sama seperti Java saat mengimplementasikan collection. Kita bebas mengimplementasikan collection pilihan kita seperti Map dan Set.

Dalam contoh berikut, kita mengimplementasikan Map dan Set menggunakan built-in method yang berbeda.


fun main(args: Array<String>) {
   val items = listOf(1, 2, 3, 4)
   println("First Element of our list----"+items.first())
   println("Last Element of our list----"+items.last())
   println("Even Numbers of our List----"+items.
      filter { it % 2 = = 0 })   // returns [2, 4]
   
   val readWriteMap = hashMapOf("foo" to 1, "bar" to 2)
   println(readWriteMap["foo"])  // prints "1"
   
   val strings = hashSetOf("a", "b", "c", "c")
   println("My Set Values are"+strings)
}

Potongan code di atas menghasilkan output berikut.

First Element of our list----1
Last Element of our list----4
Even Numbers of our List----[2, 4]
1
My Set Values are[a, b, c]

Range

Range adalah karakteristik unik lain dari Kotlin. Seperti Haskell, ia menyediakan operator yang membantu kita beralih melalui Range. Secara internal, ini diimplementasikan menggunakan rangeTo() dan bentuk operatornya adalah (..).

Dalam contoh berikut, kita akan melihat bagaimana Kotlin menginterpretasikan operator range.

fun main(args: Array<String>) {
   val i:Int  = 2
   for (j in 1..4) 
   print(j) // prints "1234"
   
   if (i in 1..10) { // equivalent of 1 < = i && i < = 10
      println("we found your number --"+i)
   }
}

Potongan code di atas menghasilkan output berikut.

1234we found your number --2

Kotlin - Control Flow

Pada bagian sebelumnya kita telah mempelajari tentang berbagai tipe data yang tersedia di Kotlin. Pada bagian ini, kita akan membahas berbagai jenis mekanisme flow control yang tersedia di Kotlin.

If - Else

Kotlin is a functional language hence like every functional language in Kotlin “if” is an expression, it is not a keyword. The expression “if” will return a value whenever necessary. Like other programming language, “if-else” block is used as an initial conditional checking operator. In the following example, we will compare two variables and provide the required output accordingly.

Kotlin adalah bahasa fungsional maka seperti setiap bahasa fungsional di Kotlin "jika" adalah ekspresi, itu bukan kata kunci. Ekspresi "jika" akan mengembalikan nilai kapan pun diperlukan. Seperti bahasa pemrograman lainnya, blok “if-else” digunakan sebagai operator pengecekan kondisi awal. Dalam contoh berikut, kami akan membandingkan dua variabel dan memberikan output yang diperlukan.

fun main(args: Array<String>) {
   val a:Int = 5
   val b:Int = 2
   var max: Int
   
   if (a > b) {
      max = a
   } else {
      max = b
   }
   print("Maximum of a or b is " +max)
 
   // As expression 
   // val max = if (a > b) a else b
}

The above piece of code yields the following output as a result in the browser. Our example also contains another line of code, which depicts how to use “If” statement as an expression.

Potongan kode di atas menghasilkan output berikut sebagai hasilnya di browser. Contoh kami juga berisi baris kode lain, yang menggambarkan cara menggunakan pernyataan "Jika" sebagai ekspresi.


Maximum of a or b is 5

Use of When

If you are familiar with other programming languages, then you might have heard of the term switch statement, which is basically a conditional operator when multiple conditions can be applied on a particular variable. “when” operator matches the variable value against the branch conditions. If it is satisfying the branch condition then it will execute the statement inside that scope. In the following example, we will learn more about “when” in Kotlin.

Jika Anda terbiasa dengan bahasa pemrograman lain, maka Anda mungkin pernah mendengar istilah pernyataan switch, yang pada dasarnya adalah operator kondisional ketika beberapa kondisi dapat diterapkan pada variabel tertentu. Operator "ketika" mencocokkan nilai variabel dengan kondisi cabang. Jika memenuhi kondisi cabang maka itu akan mengeksekusi pernyataan di dalam lingkup itu. Dalam contoh berikut, kita akan mempelajari lebih lanjut tentang “kapan” di Kotlin.

fun main(args: Array<String>) {
   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 piece of code yields the following output in the browser.

Potongan kode di atas menghasilkan output berikut di browser.

x is neither 1 nor 2


In the above example, Kotlin compiler matches the value of x with the given branches. If it is not matching any of the branches, then it will execute the else part. Practically, when is equivalent to multiple if block. Kotlin provides another flexibility to the developer, where the developer can provide multiple checks in the same line by providing “,” inside the checks. Let us modify the above example as follows.

Pada contoh di atas, compiler Kotlin mencocokkan nilai x dengan cabang yang diberikan. Jika tidak cocok dengan salah satu cabang, maka itu akan mengeksekusi bagian lain. Praktis, ketika setara dengan beberapa blok if. Kotlin memberikan fleksibilitas lain kepada pengembang, di mana pengembang dapat memberikan beberapa pemeriksaan di baris yang sama dengan memberikan "," di dalam tanda centang. Mari kita ubah contoh di atas sebagai berikut.

fun main(args: Array<String>) {
   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 in the browser, which will yield the following output in the browser.

Jalankan yang sama di browser, yang akan menghasilkan output berikut di browser.

x is neither 1 nor 2

For Loop

Loop is such an invention that provides the flexibility to iterate through any kind of data structure. Like other programming languages, Kotlin also provides many kinds of Looping methodology, however, among them “For” is the most successful one. The implementation and use of For loop is conceptually similar to Java for loop. The following example shows how we can use the same in real-life examples.

Loop adalah penemuan yang memberikan fleksibilitas untuk beralih melalui segala jenis struktur data. Seperti bahasa pemrograman lainnya, Kotlin juga menyediakan berbagai macam metodologi Looping, namun di antaranya “For” yang paling sukses. Implementasi dan penggunaan For loop secara konseptual mirip dengan Java for loop. Contoh berikut menunjukkan bagaimana kita dapat menggunakan hal yang sama dalam contoh kehidupan nyata.


fun main(args: Array<String>) {
   val items = listOf(1, 2, 3, 4)
   for (i in items) 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 iterating through that defined list and printing its value in the browser. Following is the output.

Pada potongan kode di atas, kami telah mendeklarasikan satu daftar bernama "item" dan menggunakan for loop kami mengulangi daftar yang ditentukan dan mencetak nilainya di browser. Berikut adalah outputnya.

values of the array1
values of the array2
values of the array3
values of the array4

Following is another example of code, where we are using some library function to make our development work easier than ever before.

Berikut adalah contoh kode lain, di mana kami menggunakan beberapa fungsi perpustakaan untuk membuat pengembangan kami bekerja lebih mudah dari sebelumnya.


fun main(args: Array<String>) {
   val items = listOf(1, 22, 83, 4)
   
   for ((index, value) in items.withIndex()) {
      println("the element at $index is $value")
   }
}

Once we compile and execute the above piece of code in our coding ground, it will yield the following output in the browser.

Setelah kami mengkompilasi dan mengeksekusi potongan kode di atas di dasar pengkodean kami, itu akan menghasilkan output berikut di browser.


the element at 0 is 1
the element at 1 is 22
the element at 2 is 83
the element at 3 is 4

While Loop and Do-While Loop

While and Do-While work exactly in a similar way like they do in other programming languages. The only difference between these two loops is, in case of Do-while loop the condition will be tested at the end of the loop. The following example shows the usage of the While loop.

While dan Do-While bekerja persis dengan cara yang sama seperti yang mereka lakukan dalam bahasa pemrograman lain. Satu-satunya perbedaan antara kedua loop ini adalah, dalam kasus loop Do-while, kondisinya akan diuji pada akhir loop. Contoh berikut menunjukkan penggunaan loop While.


fun main(args: Array<String>) {
   var x:Int = 0
   println("Example of While Loop--")
   
   while(x< = 10) {
      println(x)
      x++
   } 
}

The above piece of code yields the following output in the browser.

Potongan kode di atas menghasilkan output berikut di browser.

Example of While Loop--
0
1
2
3
4
5
6
7
8
9
10

Kotlin also has another loop called Do-While loop, where the loop body will be executed once, only then the condition will be checked. The following example shows the usage of the Do-while loop.

Kotlin juga memiliki loop lain yang disebut loop Do-While, di mana tubuh loop akan dieksekusi satu kali, baru kemudian kondisinya akan diperiksa. Contoh berikut menunjukkan penggunaan loop Do-while.

fun main(args: Array<String>) {
   var x:Int = 0
   do {
      x = x + 10
      println("I am inside Do block---"+x)
   } while(x <= 50)
}

The above piece of code yields the following output in the browser. In the above code, Kotlin compiler will execute the DO block, then it will go for condition checking in while block.

Potongan kode di atas menghasilkan output berikut di browser. Pada kode di atas, compiler Kotlin akan mengeksekusi blok DO, kemudian akan melakukan pengecekan kondisi pada blok while.


I am inside Do block---10
I am inside Do block---20
I am inside Do block---30
I am inside Do block---40
I am inside Do block---50
I am inside Do block---60

Use of Return, Break, Continue

If you are familiar with any programming language, then you must have an idea of different keywords that help us implement good control flow in the application. Following are the different keywords that can be used to control the loops or any other types of control flow.

Jika Anda terbiasa dengan bahasa pemrograman apa pun, maka Anda harus memiliki gagasan tentang kata kunci yang berbeda yang membantu kami menerapkan aliran kontrol yang baik dalam aplikasi. Berikut ini adalah kata kunci yang berbeda yang dapat digunakan untuk mengontrol loop atau jenis aliran kontrol lainnya.

Return − Return is a keyword that returns some value to the calling function from the called function. In the following example, we will implement this scenario using our Kotlin coding ground.

Return Return adalah kata kunci yang mengembalikan beberapa nilai ke fungsi pemanggil dari fungsi yang dipanggil. Dalam contoh berikut, kami akan menerapkan skenario ini menggunakan dasar pengkodean Kotlin kami.

fun main(args: Array<String>) {
   var x:Int = 10
   println("The value of X is--"+doubleMe(x))
}
fun doubleMe(x:Int):Int {
   return 2*x;
}

In the above piece of code, we are calling another function and multiplying the input with 2, and returning the resultant value to the called function that is our main function. Kotlin defines the function in a different manner that we will look at in a subsequent chapter. For now, it is enough to understand that the above code will generate the following output in the browser.

Pada potongan kode di atas, kita memanggil fungsi lain dan mengalikan input dengan 2, dan mengembalikan nilai yang dihasilkan ke fungsi yang dipanggil yang merupakan fungsi utama kita. Kotlin mendefinisikan fungsi dengan cara yang berbeda yang akan kita lihat di bab berikutnya. Untuk saat ini, cukup dipahami bahwa kode di atas akan menghasilkan output berikut di browser.


The value of X is--20

Continue & Break − Continue and break are the most vital part of a logical problem. The “break” keyword terminates the controller flow if some condition has failed and “continue” does the opposite. All this operation happens with immediate visibility. Kotlin is smarter than other programming languages, wherein the developer can apply more than one label as visibility. The following piece of code shows how we are implementing this label in Kotlin.

Continue & Break Continue and break adalah bagian terpenting dari masalah logis. Kata kunci "break" menghentikan aliran pengontrol jika beberapa kondisi gagal dan "lanjutkan" melakukan sebaliknya. Semua operasi ini terjadi dengan visibilitas langsung. Kotlin lebih pintar dari bahasa pemrograman lain, di mana pengembang dapat menerapkan lebih dari satu label sebagai visibilitas. Potongan kode berikut menunjukkan bagaimana kami menerapkan label ini di Kotlin.


fun main(args: Array<String>) {
   println("Example of Break and Continue")
   myLabel@ for(x in 1..10) { // appling the custom label
      if(x = = 5) {
         println("I am inside if block with value"+x+"\n-- hence it will close the operation")
         break@myLabel //specifing the label
      } else {
         println("I am inside else block with value"+x)
         continue@myLabel
      }
   }
}

The above piece of code yields the following output in the browser.

Potongan kode di atas menghasilkan output berikut di browser.

Example of Break and Continue
I am inside else block with value1
I am inside else block with value2
I am inside else block with value3
I am inside else block with value4
I am inside if block with value5
-- hence it will close the operation

As you can see, the controller continues the loop, until and unless the value of x is 5. Once the value of x reaches 5, it starts executing the if block and once the break statement is reached, the entire control flow terminates the program execution.

Seperti yang Anda lihat, pengontrol melanjutkan loop, sampai dan kecuali nilai x adalah 5. Setelah nilai x mencapai 5, ia mulai mengeksekusi blok if dan setelah pernyataan break tercapai, seluruh aliran kontrol menghentikan program. eksekusi.

Kotlin - Class & Object

In this chapter, we will learn the basics of Object-Oriented Programming (OOP) using Kotlin. We will learn about class and its object and how to play with that object. By definition of OOP, a class is a blueprint of a runtime entity and object is its state, which includes both its behavior and state. In Kotlin, class declaration consists of a class header and a class body surrounded by curly braces, similar to Java.

Dalam bab ini, kita akan mempelajari dasar-dasar Pemrograman Berorientasi Objek (OOP) menggunakan Kotlin. Kita akan belajar tentang kelas dan objeknya serta cara bermain dengan objek tersebut. Menurut definisi OOP, kelas adalah cetak biru entitas runtime dan objek adalah statusnya, yang mencakup perilaku dan statusnya. Di Kotlin, deklarasi kelas terdiri dari header kelas dan badan kelas yang dikelilingi oleh kurung kurawal, mirip dengan Java.


Class myClass { // class Header 

   // class Body
}

Like Java, Kotlin also allows to create several objects of a class and you are free to include its class members and functions. We can control the visibility of the class members variables using different keywords that we will learn in Chapter 10 – Visibility Control. In the following example, we will create one class and its object through which we will access different data members of that class.

Seperti Java, Kotlin juga memungkinkan untuk membuat beberapa objek dari sebuah kelas dan Anda bebas untuk memasukkan anggota dan fungsi kelasnya. Kita dapat mengontrol visibilitas variabel anggota kelas menggunakan kata kunci yang berbeda yang akan kita pelajari di Bab 10 – Kontrol Visibilitas. Dalam contoh berikut, kita akan membuat satu kelas dan objeknya di mana kita akan mengakses anggota data yang berbeda dari kelas itu.


class myClass {
   // property (data member)
   private var name: String = "Tutorials.point"
   
   // member function
   fun printMe() {
      print("You are at the best Learning website Named-"+name)
   }
}
fun main(args: Array<String>) {
   val obj = myClass() // create obj object of myClass class
   obj.printMe()
}

The above piece of code will yield the following output in the browser, where we are calling printMe() of myClass using its own object.

Potongan kode di atas akan menghasilkan output berikut di browser, di mana kita berada memanggil printMe() dari myClass menggunakan objeknya sendiri.


You are at the best Learning website Named- Tutorials.point

Nested Class

By definition, when a class has been created inside another class, then it is called as a nested class. In Kotlin, nested class is by default static, hence, it can be accessed without creating any object of that class. In the following example, we will see how Kotlin interprets our nested class.

Menurut definisi, ketika sebuah kelas telah dibuat di dalam kelas lain, maka itu disebut sebagai kelas bersarang. Di Kotlin, kelas bersarang secara default statis, oleh karena itu, dapat diakses tanpa membuat objek apa pun dari kelas itu. Dalam contoh berikut, kita akan melihat bagaimana Kotlin menginterpretasikan kelas bersarang kita.


fun main(args: Array<String>) {
   val demo = Outer.Nested().foo() // calling nested class method
   print(demo)
}
class Outer {
   class Nested {
      fun foo() = "Welcome to The TutorialsPoint.com"
   }
}

The above piece of code will yield the following output in the browser.

Potongan kode di atas akan menghasilkan output berikut di browser.


Welcome to The TutorialsPoint.com

Inner Class

When a nested class is marked as a “inner”, then it will be called as an Inner class. An inner class can be accessed by the data member of the outer class. In the following example, we will be accessing the data member of the outer class.

Ketika kelas bersarang ditandai sebagai "dalam", maka itu akan disebut sebagai kelas dalam. Kelas dalam dapat diakses oleh anggota data kelas luar. Pada contoh berikut, kita akan mengakses data member dari outer class.

fun main(args: Array<String>) {
   val demo = Outer().Nested().foo() // calling nested class method
   print(demo)
}
class Outer {
   private val welcomeMessage: String = "Welcome to the TutorialsPoint.com"
   inner class Nested {
      fun foo() = welcomeMessage
   }
}

The above piece of code will yield the following output in the browser, where we are calling the nested class using the default constructor provided by Kotlin compilers at the time of compiling.

Potongan kode di atas akan menghasilkan output berikut di browser, di mana kita memanggil kelas bersarang menggunakan konstruktor default yang disediakan oleh kompiler Kotlin pada saat kompilasi.

Welcome to the TutorialsPoint.com

Anonymous Inner Class

Anonymous inner class is a pretty good concept that makes the life of a programmer very easy. Whenever we are implementing an interface, the concept of anonymous inner block comes into picture. The concept of creating an object of interface using runtime object reference is known as anonymous class. In the following example, we will create an interface and we will create an object of that interface using Anonymous Inner class mechanism.

Kelas dalam anonim adalah konsep yang cukup bagus yang membuat kehidupan seorang programmer menjadi sangat mudah. Setiap kali kami mengimplementasikan antarmuka, konsep blok dalam anonim muncul. Konsep membuat objek antarmuka menggunakan referensi objek runtime dikenal sebagai kelas anonim. Pada contoh berikut, kita akan membuat sebuah interface dan kita akan membuat objek dari interface tersebut menggunakan mekanisme Anonymous Inner class.

fun main(args: Array<String>) {
   var programmer :Human = object:Human // creating an instance of the interface {
      override fun think() { // overriding the think method
         print("I am an example of Anonymous Inner Class ")
      }
   }
   programmer.think()
}
interface Human {
   fun think()
}

The above piece of code will yield the following output in the browser.

Potongan kode di atas akan menghasilkan output berikut di browser.

I am an example of Anonymous Inner Class

Type Aliases

Type aliases are a property of Kotlin compiler. It provides the flexibility of creating a new name of an existing type, it does not create a new type. If the type name is too long, you can easily introduce a shorter name and use the same for future usage. Type aliases is really helpful for complex type. In the latest version, Kotlin revoked the support for type aliases, however, if you are using an old version of Kotlin you may have use it like the following −

Alias tipe adalah properti kompiler Kotlin. Ini memberikan fleksibilitas untuk membuat nama baru dari tipe yang ada, tidak membuat tipe baru. Jika nama jenis terlalu panjang, Anda dapat dengan mudah memperkenalkan nama yang lebih pendek dan menggunakan yang sama untuk penggunaan di masa mendatang. Ketik alias sangat membantu untuk tipe kompleks. Di versi terbaru, Kotlin mencabut dukungan untuk alias tipe, namun, jika Anda menggunakan Kotlin versi lama, Anda mungkin menggunakannya seperti berikut

typealias NodeSet = Set<Network.Node>
typealias FileTable<K> = MutableMap<K, MutableList<File>>

Kotlin - Constructors

In this chapter, we will learn about constructors in Kotlin. Kotlin has two types of constructor - one is the primary constructor and the other is the secondary constructor. One Kotlin class can have one primary constructor, and one or more secondary constructor. Java constructor initializes the member variables, however, in Kotlin the primary constructor initializes the class, whereas the secondary constructor helps to include some extra logic while initializing the same. The primary constructor can be declared at class header level as shown in the following example.

Dalam bab ini, kita akan belajar tentang konstruktor di Kotlin. Kotlin memiliki dua jenis konstruktor - satu adalah konstruktor utama dan yang lainnya adalah konstruktor sekunder. Satu kelas Kotlin dapat memiliki satu konstruktor utama, dan satu atau lebih konstruktor sekunder. Konstruktor Java menginisialisasi variabel anggota, namun, di Kotlin konstruktor utama menginisialisasi kelas, sedangkan konstruktor sekunder membantu memasukkan beberapa logika tambahan saat menginisialisasi yang sama. Konstruktor utama dapat dideklarasikan pada tingkat header kelas seperti yang ditunjukkan pada contoh berikut.


class Person(val firstName: String, var age: Int) {
   // class body
}

In the above example, we have declared the primary constructor inside the parenthesis. Among the two fields, first name is read-only as it is declared as “val”, while the field age can be edited. In the following example, we will use the primary constructor.

Dalam contoh di atas, kami telah mendeklarasikan konstruktor utama di dalam tanda kurung. Di antara dua bidang, nama depan hanya-baca karena dinyatakan sebagai "val", sedangkan usia bidang dapat diedit. Dalam contoh berikut, kita akan menggunakan konstruktor utama.


fun main(args: Array<String>) {
   val person1 = Person("TutorialsPoint.com", 15)
   println("First Name = ${person1.firstName}")
   println("Age = ${person1.age}")
}
class Person(val firstName: String, var age: Int) {
}

The above piece of code will automatically initialize the two variables and provide the following output in the browser.

Potongan kode di atas akan secara otomatis menginisialisasi kedua variabel dan memberikan output berikut di browser.

First Name = TutorialsPoint.com
Age = 15

As mentioned earlier, Kotlin allows to create one or more secondary constructors for your class. This secondary constructor is created using the “constructor” keyword. It is required whenever you want to create more than one constructor in Kotlin or whenever you want to include more logic in the primary constructor and you cannot do that because the primary constructor may be called by some other class. Take a look at the following example, where we have created a secondary constructor and are using the above example to implement the same.

Seperti disebutkan sebelumnya, Kotlin memungkinkan untuk membuat satu atau beberapa konstruktor sekunder untuk kelas Anda. Konstruktor sekunder ini dibuat menggunakan kata kunci "konstruktor". Itu diperlukan setiap kali Anda ingin membuat lebih dari satu konstruktor di Kotlin atau kapan pun Anda ingin memasukkan lebih banyak logika dalam konstruktor utama dan Anda tidak dapat melakukannya karena konstruktor utama dapat dipanggil oleh beberapa kelas lain. Lihatlah contoh berikut, di mana kita telah membuat konstruktor sekunder dan menggunakan contoh di atas untuk mengimplementasikan hal yang sama.


fun main(args: Array<String>) {
   val HUman = HUman("TutorialsPoint.com", 25)
   print("${HUman.message}"+"${HUman.firstName}"+
      "Welcome to the example of Secondary  constructor, Your Age is-${HUman.age}")
}
class HUman(val firstName: String, var age: Int) {
   val message:String  = "Hey!!!"
	constructor(name : String , age :Int ,message :String):this(name,age) {
   }
}

Note − Any number of secondary constructors can be created, however, all of those constructors should call the primary constructor directly or indirectly.

Catatan Sejumlah konstruktor sekunder dapat dibuat, namun semua konstruktor tersebut harus memanggil konstruktor utama secara langsung atau tidak langsung.


The above piece of code will yield the following output in the browser.

Potongan kode di atas akan menghasilkan output berikut di browser.


Hey!!! TutorialsPoint.comWelcome to the example of Secondary constructor, Your Age is- 25

Kotlin - Inheritance

In this chapter, we will learn about inheritance. By definition, we all know that inheritance means accruing some properties of the mother class into the child class. In Kotlin, the base class is named as “Any”, which is the super class of the ‘any’ default class declared in Kotlin. Like all other OOPS, Kotlin also provides this functionality using one keyword known as “:”.

Dalam bab ini, kita akan belajar tentang pewarisan. Menurut definisi, kita semua tahu bahwa pewarisan berarti memperoleh beberapa properti dari kelas ibu ke dalam kelas anak. Di Kotlin, kelas dasar diberi nama “Any”, yang merupakan kelas super dari kelas default 'apa saja' yang dideklarasikan di Kotlin. Seperti semua OOPS lainnya, Kotlin juga menyediakan fungsionalitas ini menggunakan satu kata kunci yang dikenal sebagai “:”.


Everything in Kotlin is by default final, hence, we need to use the keyword “open” in front of the class declaration to make it allowable to inherit. Take a look at the following example of inheritance.

Semua yang ada di Kotlin secara default adalah final, oleh karena itu, kita perlu menggunakan kata kunci “open” di depan deklarasi kelas agar dapat diwarisi. Perhatikan contoh pewarisan berikut.


import java.util.Arrays

open class ABC {
   fun think () {
      print("Hey!! i am thiking ")
   }
}
class BCD: ABC(){ // inheritence happend using default constructor 
}

fun main(args: Array<String>) {
   var  a = BCD()
   a.think()
}

The above piece of code will yield the following output in the browser.

Potongan kode di atas akan menghasilkan output berikut di browser.

Hey!! i am thiking

Now, what if we want to override the think() method in the child class. Then, we need to consider the following example where we are creating two classes and override one of its function into the child class.

Sekarang, bagaimana jika kita ingin mengganti metode think() di kelas anak. Kemudian, kita perlu mempertimbangkan contoh berikut di mana kita membuat dua kelas dan menimpa salah satu fungsinya ke dalam kelas anak.


import java.util.Arrays

open class ABC {
   open fun think () {
      print("Hey!! i am thinking ")
   }
}
class BCD: ABC() { // inheritance happens using default constructor 
   override fun think() {
      print("I Am from Child")
   }
}
fun main(args: Array<String>) {
   var  a = BCD()
   a.think()
}

The above piece of code will call the child class inherited method and it will yield the following output in the browser. Like Java, Kotlin too doesn’t allow multiple inheritances.

Potongan kode di atas akan memanggil metode turunan kelas anak dan akan menghasilkan output berikut di browser. Seperti Java, Kotlin juga tidak mengizinkan banyak pewarisan.

I Am from Child

Kotlin - Interface

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.

Dalam bab ini, kita akan belajar tentang antarmuka di Kotlin. Di Kotlin, antarmuka bekerja persis seperti Java 8, yang berarti mereka dapat berisi implementasi metode serta deklarasi metode abstrak. Antarmuka dapat diimplementasikan oleh kelas untuk menggunakan fungsionalitas yang ditentukan. Kami telah memperkenalkan contoh dengan antarmuka di Bab 6 - bagian "kelas dalam anonim". Dalam bab ini, kita akan belajar lebih banyak tentangnya. Kata kunci “antarmuka” digunakan untuk mendefinisikan antarmuka di Kotlin seperti yang ditunjukkan pada potongan kode berikut.


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.

Dalam contoh di atas, kami telah membuat satu antarmuka bernama "ExampleInterface" dan di dalamnya kami memiliki beberapa properti abstrak dan metode bersama-sama. Lihat fungsi bernama “sayHello()”, yang merupakan metode yang diimplementasikan.

In the following example, we will be implementing the above interface in a class.

Dalam contoh berikut, kita akan mengimplementasikan antarmuka di atas dalam sebuah kelas.

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.

Potongan kode di atas akan menghasilkan output berikut di 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.

Seperti yang disebutkan sebelumnya, Kotlin tidak mendukung banyak pewarisan, namun, hal yang sama dapat dicapai dengan mengimplementasikan lebih dari dua antarmuka sekaligus.

Pada contoh berikut, kita akan membuat dua interface dan nantinya kita akan mengimplementasikan kedua interface tersebut ke dalam sebuah class.


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.

Dalam contoh di atas, kami telah membuat dua antarmuka sampel A, B dan di kelas bernama "multipleInterfaceExample" kami telah mengimplementasikan dua antarmuka yang dideklarasikan sebelumnya. Potongan kode di atas akan menghasilkan output berikut di browser.

method of interface A
I am another Method from interface B

Kotlin - Visibility Control

In this chapter, we will learn about different modifiers available in Kotlin language. Access modifier is used to restrict the usage of the variables, methods and class used in the application. Like other OOP programming language, this modifier is applicable at multiple places such as in the class header or method declaration. There are four access modifiers available in Kotlin.

Dalam bab ini, kita akan mempelajari tentang berbagai pengubah yang tersedia dalam bahasa Kotlin. Access modifier digunakan untuk membatasi penggunaan variabel, metode dan kelas yang digunakan dalam aplikasi. Seperti bahasa pemrograman OOP lainnya, pengubah ini berlaku di banyak tempat seperti di header kelas atau deklarasi metode. Ada empat pengubah akses yang tersedia di Kotlin.


Private

The classes, methods, and packages can be declared with a private modifier. Once anything is declared as private, then it will be accessible within its immediate scope. For instance, a private package can be accessible within that specific file. A private class or interface can be accessible only by its data members, etc.

Kelas, metode, dan paket dapat dideklarasikan dengan pengubah pribadi. Setelah sesuatu dinyatakan sebagai pribadi, maka itu akan dapat diakses dalam lingkup langsungnya. Misalnya, paket pribadi dapat diakses di dalam file tertentu. Kelas atau antarmuka pribadi hanya dapat diakses oleh anggota datanya, dll.

private class privateExample {
   private val i = 1
   private val doSomething() {
   }
}

In the above example, the class “privateExample” and the variable i both can be accessible only in the same Kotlin file, where its mentioned as they all are declared as private in the declaration block.

Dalam contoh di atas, kelas “privateExample” dan variabel i keduanya hanya dapat diakses di file Kotlin yang sama, di mana disebutkan karena semuanya dideklarasikan sebagai pribadi di blok deklarasi.

Protected

Protected is another access modifier for Kotlin, which is currently not available for top level declaration like any package cannot be protected. A protected class or interface is visible to its subclass only.

Dilindungi adalah pengubah akses lain untuk Kotlin, yang saat ini tidak tersedia untuk deklarasi tingkat atas seperti paket apa pun yang tidak dapat dilindungi. Kelas atau antarmuka yang dilindungi hanya dapat dilihat oleh subkelasnya.

class A() {
   protected val i = 1
}
class B : A() {
   fun getValue() : Int {
      return i
   }
}

In the above example, the variable “i” is declared as protected, hence, it is only visible to its subclass.

Pada contoh di atas, variabel “i” dideklarasikan sebagai protected, sehingga hanya dapat dilihat oleh subkelasnya.

Internal

Internal is a newly added modifier introduced in Kotlin. If anything is marked as internal, then that specific field will be in the internal field. An Internal package is visible only inside the module under which it is implemented. An internal class interface is visible only by other class present inside the same package or the module. In the following example, we will see how to implement an internal method.

Internal adalah pengubah baru yang ditambahkan yang diperkenalkan di Kotlin. Jika ada yang ditandai sebagai internal, maka bidang khusus itu akan berada di bidang internal. Paket internal hanya terlihat di dalam modul yang diimplementasikan. Antarmuka kelas internal hanya terlihat oleh kelas lain yang ada di dalam paket atau modul yang sama. Dalam contoh berikut, kita akan melihat bagaimana menerapkan metode internal.

class internalExample {
   internal val i = 1
   internal fun doSomething() {
   } 
}

In the above example, the method named “doSomething” and the variable is mentioned as internal, hence, these two fields can be accessible only inside the package under which it is declared.

Dalam contoh di atas, metode bernama "doSomething" dan variabel disebutkan sebagai internal, oleh karena itu, kedua bidang ini hanya dapat diakses di dalam paket di mana ia dideklarasikan.

Public

Public modifier is accessible from anywhere in the project workspace. If no access modifier is specified, then by default it will be in the public scope. In all our previous examples, we have not mentioned any modifier, hence, all of them are in the public scope. Following is an example to understand more on how to declare a public variable or method.

Pengubah publik dapat diakses dari mana saja di ruang kerja proyek. Jika tidak ada pengubah akses yang ditentukan, maka secara default itu akan berada di ruang lingkup publik. Dalam semua contoh kami sebelumnya, kami belum menyebutkan pengubah apa pun, oleh karena itu, semuanya berada dalam ruang lingkup publik. Berikut ini adalah contoh untuk lebih memahami cara mendeklarasikan variabel atau metode publik.


class publicExample {
   val i = 1
   fun doSomething() {
   }
}

In the above example, we have not mentioned any modifier, thus all these methods and variables are by default public.

Dalam contoh di atas, kami belum menyebutkan pengubah apa pun, sehingga semua metode dan variabel ini secara default adalah publik.

Kotlin - Extension

In this chapter, we will learn about another new feature of Kotlin named “Extension”. Using extension, we will be able to add or remove some method functionality even without inheriting or modifying them. Extensions are resolved statistically. It does not actually modify the existing class, but it creates a callable function that can be called with a dot operation.

Dalam bab ini, kita akan mempelajari tentang fitur baru lain dari Kotlin bernama “Extension”. Dengan menggunakan ekstensi, kita akan dapat menambah atau menghapus beberapa fungsi metode bahkan tanpa mewarisi atau memodifikasinya. Ekstensi diselesaikan secara statistik. Itu tidak benar-benar mengubah kelas yang ada, tetapi menciptakan fungsi yang dapat dipanggil yang dapat dipanggil dengan operasi titik.


Function Extension

In function extension, Kotlin allows to define a method outside of the main class. In the following example, we will see how the extension is implemented at the functional level.

Dalam ekstensi fungsi, Kotlin memungkinkan untuk mendefinisikan metode di luar kelas utama. Dalam contoh berikut, kita akan melihat bagaimana ekstensi diimplementasikan pada tingkat fungsional.


class Alien {
   var skills : String = "null" 
	
   fun printMySkills() {
      print(skills)
   }		
 }
fun main(args: Array<String>) {
   var  a1 = Alien()
   a1.skills = "JAVA"
   //a1.printMySkills()
   var  a2 = Alien()
   a2.skills = "SQL"
   //a2.printMySkills() 
	
   var  a3 = Alien()
   a3.skills = a1.addMySkills(a2)
   a3.printMySkills()
}
fun Alien.addMySkills(a:Alien):String{
   var a4 = Alien()
   a4.skills = this.skills + " " +a.skills
   return a4.skills
}

In the above example, we don’t have any method inside “Alien” class named as “addMySkills()”, however, we still are implementing the same method somewhere else outside of the class, This is the magic of extension.

The above piece of code will generate the following output in the browser.

Dalam contoh di atas, kami tidak memiliki metode apa pun di dalam kelas "Alien" bernama "addMySkills()", namun, kami masih menerapkan metode yang sama di tempat lain di luar kelas, Ini adalah keajaiban ekstensi.

Potongan kode di atas akan menghasilkan output berikut di browser.


JAVA SQL

Object Extension

Kotlin provides another mechanism to implement static functionality of Java. This can be achieved using the keyword “companion object”. Using this mechanism, we can create an object of a class inside a factory method and later we can just call that method using the reference of the class name. In the following example, we will create a “companion object”.


Kotlin provides another mechanism to implement static functionality of Java. This can be achieved using the keyword “companion object”. Using this mechanism, we can create an object of a class inside a factory method and later we can just call that method using the reference of the class name. In the following example, we will create a “companion object”.


fun main(args: Array<String>) {
   println("Heyyy!!!"+A.show())
}
class A {
   companion object {
      fun show():String {
         return("You are learning Kotlin from TutorialsPoint.com")
      }
   }
}

The above piece of code will yield the following output in the browser.

Potongan kode di atas akan menghasilkan output berikut di browser.

Heyyy!!! You are learning Kotlin from TutorialsPoint.com


Kotlin - Data Classes

In this chapter, we will learn more about Data classes of Kotlin programming language. A class can be marked as a Data class whenever it is marked as ”data”. This type of class can be used to hold the basic data apart. Other than this, it does not provide any other functionality.

Dalam bab ini, kita akan mempelajari lebih lanjut tentang kelas Data bahasa pemrograman Kotlin. Kelas dapat ditandai sebagai kelas Data setiap kali ditandai sebagai "data". Jenis kelas ini dapat digunakan untuk memisahkan data dasar. Selain ini, itu tidak menyediakan fungsionalitas lain.

All the data classes need to have one primary constructor and all the primary constructor should have at least one parameter. Whenever a class is marked as data, we can use some of the inbuilt function of that data class such as “toString()”,”hashCode()”, etc. Any data class cannot have a modifier like abstract and open or internal. Data class can be extended to other classes too. In the following example, we will create one data class.

Semua kelas data harus memiliki satu konstruktor utama dan semua konstruktor utama harus memiliki setidaknya satu parameter. Setiap kali sebuah kelas ditandai sebagai data, kita dapat menggunakan beberapa fungsi bawaan dari kelas data tersebut seperti “toString()”,”hashCode()”, dll. Setiap kelas data tidak dapat memiliki pengubah seperti abstract dan open atau internal. Kelas data dapat diperluas ke kelas lain juga. Dalam contoh berikut, kita akan membuat satu kelas data.



fun main(args: Array<String>) {
   val book: Book = Book("Kotlin", "TutorialPoint.com", 5)
   println("Name of the Book is--"+book.name) // "Kotlin"
   println("Puclisher Name--"+book.publisher) // "TutorialPoint.com"
   println("Review of the book is--"+book.reviewScore) // 5
   book.reviewScore = 7
   println("Printing all the info all together--"+book.toString()) 
   //using inbuilt function of the data class 
   
   println("Example of the hashCode function--"+book.hashCode())
}

data class Book(val name: String, val publisher: String, var 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 accessed all of its data members.

kelas data Buku (nama val: String, penerbit val: String, var reviewScore: Int) Potongan kode di atas akan menghasilkan output berikut di browser, di mana kami telah membuat satu kelas data untuk menampung beberapa data, dan dari fungsi utama kami telah mengakses semua anggota datanya.


Name of the Book is--"Kotlin"
Puclisher Name--"TutorialPoint.com"
Review of the book is--5
Printing all the info all together--(name-Kotlin, publisher-TutorialPoint.com, reviewScore-7)
Example of the hashCode function---1753517245

Kotlin - Sealed Class

In this chapter, we will learn about another class type called “Sealed” class. This type of class is used to represent a restricted class hierarchy. Sealed allows the developers to maintain a data type of a predefined type. To make a sealed class, we need to use the keyword “sealed” as a modifier of that class. A sealed class can have its own subclass but all those subclasses need to be declared inside the same Kotlin file along with the sealed class. In the following example, we will see how to use a sealed class.

Dalam bab ini, kita akan belajar tentang tipe kelas lain yang disebut kelas “Tersegel”. Jenis kelas ini digunakan untuk mewakili hierarki kelas yang dibatasi. Sealed memungkinkan pengembang untuk mempertahankan tipe data dari tipe yang telah ditentukan. Untuk membuat kelas tersegel, kita perlu menggunakan kata kunci “tersegel” sebagai pengubah kelas tersebut. Kelas yang disegel dapat memiliki subkelasnya sendiri tetapi semua subkelas tersebut perlu dideklarasikan di dalam file Kotlin yang sama bersama dengan kelas yang disegel. Dalam contoh berikut, kita akan melihat bagaimana menggunakan kelas yang disegel.

sealed class MyExample {
   class OP1 : MyExample() // MyExmaple class can be of two types only
   class OP2 : MyExample()
}
fun main(args: Array<String>) {
   val obj: MyExample = MyExample.OP2() 
   
   val output = when (obj) { // defining the object of the class depending on the inuputs 
      is MyExample.OP1 -> "Option One has been chosen"
      is MyExample.OP2 -> "option Two has been chosen"
   }
   
   println(output)
}

In the above example, we have one sealed class named “MyExample”, which can be of two types only - one is “OP1” and another one is “OP2”. In the main class, we are creating an object in our class and assigning its type at runtime. Now, as this “MyExample” class is sealed, we can apply the “when ” clause at runtime to implement the final output.

In sealed class, we need not use any unnecessary “else” statement to complex out the code. The above piece of code will yield the following output in the browser.


Dalam contoh di atas, kami memiliki satu kelas tersegel bernama "MyExample", yang hanya dapat terdiri dari dua jenis - satu adalah "OP1" dan satu lagi adalah "OP2". Di kelas utama, kami membuat objek di kelas kami dan menetapkan tipenya saat runtime. Sekarang, karena kelas "MyExample" ini disegel, kita dapat menerapkan klausa "kapan" saat runtime untuk mengimplementasikan hasil akhir.

Di kelas yang disegel, kita tidak perlu menggunakan pernyataan "lain" yang tidak perlu untuk memperumit kode. Potongan kode di atas akan menghasilkan output berikut di browser.


option Two has been chosen

Kotlin - Generics

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.


Seperti Java, Kotlin menyediakan urutan pengetikan variabel yang lebih tinggi yang disebut sebagai Generik. Dalam bab ini, kita akan mempelajari bagaimana Kotlin mengimplementasikan Generics dan bagaimana sebagai developer kita dapat menggunakan fungsionalitas yang disediakan di dalam library generics. Dari segi implementasi, generik sangat mirip dengan Java tetapi pengembang Kotlin telah memperkenalkan dua kata kunci baru “keluar” dan “masuk” untuk membuat kode Kotlin lebih mudah dibaca dan mudah bagi pengembang.

Di Kotlin, kelas dan tipe adalah konsep yang sama sekali berbeda. Sesuai contoh, List adalah kelas di Kotlin, sedangkan List<String> adalah tipe di Kotlin. Contoh berikut menggambarkan bagaimana obat generik diimplementasikan di 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.

Dalam kode di atas, kami telah mendeklarasikan satu "bilangan bulat" dan kemudian kami menetapkan variabel itu ke variabel angka. Hal ini dimungkinkan karena “Int” adalah subclass dari kelas Number, maka konversi tipe terjadi secara otomatis pada saat runtime dan menghasilkan output sebagai “1”.

Mari kita pelajari lebih lanjut tentang obat generik di Kotlin. Lebih baik menggunakan tipe data generik setiap kali kita tidak yakin tentang tipe data yang akan kita gunakan dalam aplikasi. Secara umum, di Kotlin generik didefinisikan dengan <T> di mana “T” adalah singkatan dari template, yang dapat ditentukan secara dinamis oleh compiler Kotlin. Pada contoh berikut, kita akan melihat cara menggunakan tipe data generik dalam bahasa pemrograman Kotlin.


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.

Pada potongan kode di atas, kita membuat satu kelas dengan tipe pengembalian generik, yang direpresentasikan sebagai <T>. Lihatlah metode utama, di mana kita telah mendefinisikan nilainya secara dinamis saat dijalankan dengan membuktikan tipe nilai, sambil membuat objek kelas ini. Beginilah cara generik ditafsirkan oleh kompiler Kotlin. Kami akan mendapatkan output berikut di browser, setelah kami menjalankan kode ini di tempat pengkodean kami.


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.

Ketika kita ingin menetapkan tipe generik ke salah satu tipe supernya, maka kita perlu menggunakan kata kunci "keluar", dan ketika kita ingin menetapkan tipe generik ke salah satu subtipenya, maka kita perlu menggunakan "dalam" kata kunci. Dalam contoh berikut, kita akan menggunakan kata kunci “keluar”. Demikian pula, Anda dapat mencoba menggunakan kata kunci “dalam”.

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.

Kode di atas akan menghasilkan output berikut di browser.


I am getting called with the value 10
I am getting called with the value 10.0
genericsExample@28d93b30
genericsExample@1b6d3586

Kotlin - Delegation

Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object. The following example demonstrates how this happens in Kotlin.

Kotlin mendukung pola desain “delegasi” dengan memperkenalkan kata kunci baru “oleh”. Dengan menggunakan kata kunci atau metodologi delegasi ini, Kotlin mengizinkan kelas turunan untuk mengakses semua metode publik yang diimplementasikan dari sebuah antarmuka melalui objek tertentu. Contoh berikut menunjukkan bagaimana hal ini terjadi di Kotlin.


interface Base {
   fun printMe() //abstract method
}
class BaseImpl(val x: Int) : Base {
   override fun printMe() { println(x) }   //implementation of the method
}
class Derived(b: Base) : Base by b  // delegating the public method on the object b

fun main(args: Array<String>) {
   val b = BaseImpl(10)
   Derived(b).printMe() // prints 10 :: accessing the printMe() method 
}

In the example, we have one interface “Base” with its abstract method named “printme()”. In the BaseImpl class, we are implementing this “printme()” and later from another class we are using this implementation using “by” keyword.

The above piece of code will yield the following output in the browser.

Dalam contoh, kami memiliki satu antarmuka "Basis" dengan metode abstraknya bernama "printme()". Di kelas BaseImpl, kami menerapkan "printme()" ini dan kemudian dari kelas lain kami menggunakan implementasi ini menggunakan kata kunci "oleh".

Potongan kode di atas akan menghasilkan output berikut di browser.

10

Property Delegation

In the previous section, we have learned about the delegation design pattern using “by” keyword. In this section, we will learn about delegation of properties using some standard methods mentioned in Kotlin library.

Delegation means passing the responsibility to another class or method. When a property is already declared in some places, then we should reuse the same code to initialize them. In the following examples, we will use some standard delegation methodology provided by Kotlin and some standard library function while implementing delegation in our examples.

Pada bagian sebelumnya, kita telah mempelajari pola desain delegasi menggunakan kata kunci “by”. Di bagian ini, kita akan belajar tentang pendelegasian properti menggunakan beberapa metode standar yang disebutkan di pustaka Kotlin.

Delegasi berarti menyerahkan tanggung jawab ke kelas atau metode lain. Ketika sebuah properti sudah dideklarasikan di beberapa tempat, maka kita harus menggunakan kembali kode yang sama untuk menginisialisasinya. Dalam contoh berikut, kita akan menggunakan beberapa metodologi delegasi standar yang disediakan oleh Kotlin dan beberapa fungsi library standar saat menerapkan delegasi dalam contoh kita.


Using Lazy()

Lazy is a lambda function which takes a property as an input and in return gives an instance of Lazy<T>, where <T> is basically the type of the properties it is using. Let us take a look at the following to understand how it works.

Lazy adalah fungsi lambda yang mengambil properti sebagai input dan sebagai gantinya memberikan instance Lazy<T>, di mana <T> pada dasarnya adalah jenis properti yang digunakannya. Mari kita lihat berikut ini untuk memahami cara kerjanya.

val myVar: String by lazy {
   "Hello"
}
fun main(args: Array<String>) {
   println(myVar +" My dear friend")
}

In the above piece of code, we are passing a variable “myVar” to the Lazy function, which in return assigns the value to its object and returns the same to the main function. Following is the output in the browser.

Pada potongan kode di atas, kita meneruskan variabel "myVar" ke fungsi Lazy, yang sebagai imbalannya memberikan nilai ke objeknya dan mengembalikannya ke fungsi utama. Berikut adalah output di browser.

Hello My dear friend

Delegetion.Observable()

Observable() takes two arguments to initialize the object and returns the same to the called function. In the following example, we will see how to use Observable() method in order to implement delegation.

Observable() mengambil dua argumen untuk menginisialisasi objek dan mengembalikan yang sama ke fungsi yang dipanggil. Dalam contoh berikut, kita akan melihat bagaimana menggunakan metode Observable() untuk mengimplementasikan delegasi.


import kotlin.properties.Delegates
class User {
   var name: String by Delegates.observable("Welcome to Tutorialspoint.com") {
      prop, old, new ->
      println("$old -> $new")
   }
}
fun main(args: Array<String>) {
   val user = User()
   user.name = "first"
   user.name = "second"
}

The above piece of code will yield the following output in the browser.

Potongan kode di atas akan menghasilkan output berikut di browser.

first -> second

In general, the syntax is the expression after the “by” keyword is delegated. The get() and set() methods of the variable p will be delegated to its getValue() and setValue() methods defined in the Delegate class.

Secara umum, sintaks adalah ekspresi setelah kata kunci “oleh” didelegasikan. Metode get() dan set() dari variabel p akan didelegasikan ke metode getValue() dan setValue() yang ditentukan dalam kelas Delegate.


class Example {
   var p: String by Delegate()
}

For the above piece of code, following is the delegate class that we need to generate in order to assign the value in the variable p.

Untuk potongan kode di atas, berikut adalah kelas delegasi yang perlu kita buat untuk menetapkan nilai dalam variabel p.

class Delegate {
   operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
      return "$thisRef, thank you for delegating '${property.name}' to me!"
   }
   operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
      println("$value has been assigned to '${property.name} in $thisRef.'")
   }
}

While reading, getValue() method will be called and while setting the variable setValue() method will be called.


Saat membaca, metode getValue() akan dipanggil dan saat menyetel variabel metode setValue() akan dipanggil.

Kotlin - Functions

Kotlin is a statically typed language, hence, functions play a great role in it. We are pretty familiar with function, as we are using function throughout the examples. Function is declared with the keyword “fun”. Like any other OOP, it also needs a return type and an option argument list.

In the following example, we are defining a function called MyFunction and from the main function we are calling this function and passing some argument.

Kotlin is a statically typed language, hence, functions play a great role in it. We are pretty familiar with function, as we are using function throughout the examples. Function is declared with the keyword “fun”. Like any other OOP, it also needs a return type and an option argument list.

In the following example, we are defining a function called MyFunction and from the main function we are calling this function and passing some argument.


fun main(args: Array<String>) {
   println(MyFunction("tutorialsPoint.com"))
}
fun MyFunction(x: String): String {
   var c:String  = "Hey!! Welcome To ---"
   return (c+x)
}

The above piece of code will yield the following output in the browser. Potongan kode di atas akan menghasilkan output berikut di browser.


Hey!! Welcome To ---tutorialsPoint.com

The function should be declared as follows −

Fungsi tersebut harus dideklarasikan sebagai berikut

fun <nameOfFunction>(<argument>:<argumentType>):<ReturnType>

Following are some of the different types of function available in Kotlin. Berikut adalah beberapa jenis fungsi yang tersedia di Kotlin.


Lambda Function

Lambda is a high level function that drastically reduces the boiler plate code while declaring a function and defining the same. Kotlin allows you to define your own lambda. In Kotlin, you can declare your lambda and pass that lambda to a function.

Take a look at the following example.

Lambda adalah fungsi tingkat tinggi yang secara drastis mengurangi kode pelat boiler sambil mendeklarasikan fungsi dan mendefinisikannya. Kotlin memungkinkan Anda untuk menentukan lambda Anda sendiri. Di Kotlin, Anda dapat mendeklarasikan lambda Anda dan meneruskan lambda itu ke suatu fungsi.

Perhatikan contoh berikut.


fun main(args: Array<String>) {
   val mylambda :(String)->Unit  = {s:String->print(s)}
   val v:String = "TutorialsPoint.com"
   mylambda(v)
}

In the above code, we have created our own lambda known as “mylambda” and we have passed one variable to this lambda, which is of type String and contains a value “TutorialsPoint.com”.

The above piece of code will yield the following output in the browser.

Dalam kode di atas, kami telah membuat lambda kami sendiri yang dikenal sebagai "mylambda" dan kami telah mengirimkan satu variabel ke lambda ini, yang bertipe String dan berisi nilai "TutorialsPoint.com".

Potongan kode di atas akan menghasilkan output berikut di browser.


Inline Function

The above example shows the basic of the lambda expression that we can use in Kotlin application. Now, we can pass a lambda to another function to get our output which makes the calling function an inline function.

Take a look at the following example.

Contoh di atas menunjukkan dasar dari ekspresi lambda yang dapat kita gunakan dalam aplikasi Kotlin. Sekarang, kita dapat meneruskan lambda ke fungsi lain untuk mendapatkan output kita yang membuat fungsi pemanggilan menjadi fungsi inline.

Perhatikan contoh berikut.


fun main(args: Array<String>) {
   val mylambda:(String)->Unit  = {s:String->print(s)}
   val v:String = "TutorialsPoint.com"
   myFun(v,mylambda) //passing lambda as a parameter of another function 
}
fun myFun(a :String, action: (String)->Unit) { //passing lambda 
   print("Heyyy!!!")
   action(a)// call to lambda function
}

The above piece of code will yield the following output in the browser. Using inline function, we have passed a lambda as a parameter. Any other function can be made an inline function using the “inline” keyword.

Potongan kode di atas akan menghasilkan output berikut di browser. Menggunakan fungsi inline, kami telah melewati lambda sebagai parameter. Fungsi lain apa pun dapat dibuat menjadi fungsi sebaris menggunakan kata kunci “sebaris”.


Heyyy!!!TutorialsPoint.com

Kotlin - Destructuring Declarations

Kotlin contains many features of other programming languages. It allows you to declare multiple variables at once. This technique is called Destructuring declaration.

Following is the basic syntax of the destructuring declaration.


Kotlin berisi banyak fitur dari bahasa pemrograman lain. Ini memungkinkan Anda untuk mendeklarasikan beberapa variabel sekaligus. Teknik ini disebut deklarasi Destructuring.

Berikut ini adalah sintaks dasar dari deklarasi destructuring.


val (name, age) = person

In the above syntax, we have created an object and defined all of them together in a single statement. Later, we can use them as follows.

Dalam sintaks di atas, kami telah membuat objek dan mendefinisikan semuanya bersama-sama dalam satu pernyataan. Nantinya, kita bisa menggunakannya sebagai berikut.


println(name)
println(age)

Now, let us see how we can use the same in our real-life application. Consider the following example where we are creating one Student class with some attributes and later we will be using them to print the object values.

Sekarang, mari kita lihat bagaimana kita dapat menggunakan hal yang sama dalam aplikasi kehidupan nyata kita. Perhatikan contoh berikut di mana kita membuat satu kelas Siswa dengan beberapa atribut dan nanti kita akan menggunakannya untuk mencetak nilai objek.

fun main(args: Array<String>) {
   val s = Student("TutorialsPoint.com","Kotlin")
   val (name,subject) = s
   println("You are learning "+subject+" from "+name)
}
data class Student( val a :String,val b: String ){
   var name:String = a
   var subject:String = b
}

The above piece of code will yield the following output in the browser.

Potongan kode di atas akan menghasilkan output berikut di browser.

Kotlin - Exception Handling

Exception handling is a very important part of a programming language. This technique restricts our application from generating the wrong output at runtime. In this chapter, we will learn how to handle runtime exception in Kotlin. The exceptions in Kotlin is pretty similar to the exceptions in Java. All the exceptions are descendants of the “Throwable” class. Following example shows how to use exception handling technique in Kotlin.

Penanganan eksepsi adalah bagian yang sangat penting dari bahasa pemrograman. Teknik ini membatasi aplikasi kita untuk menghasilkan output yang salah saat runtime. Dalam bab ini, kita akan mempelajari cara menangani pengecualian runtime di Kotlin. Pengecualian di Kotlin sangat mirip dengan pengecualian di Jawa. Semua pengecualian adalah turunan dari kelas "Throwable". Contoh berikut menunjukkan cara menggunakan teknik penanganan pengecualian di Kotlin.

fun main(args: Array<String>) {
   try {
      val myVar:Int = 12;
      val v:String = "Tutorialspoint.com";
      v.toInt();
   } catch(e:Exception) {
      e.printStackTrace();
   } finally {
      println("Exception Handeling in Kotlin");
   }
}

In the above piece of code, we have declared a String and later tied that string into the integer, which is actually a runtime exception. Hence, we will get the following output in the browser.

Pada potongan kode di atas, kita telah mendeklarasikan sebuah String dan kemudian mengikat string tersebut ke dalam integer, yang sebenarnya merupakan pengecualian runtime. Oleh karena itu, kita akan mendapatkan output berikut di browser.

val myVar:Int = 12;
Exception Handeling in Kotlin

Note − Like Java, Kotlin also executes the finally block after executing the catch block.

Catatan Seperti Java, Kotlin juga mengeksekusi blok akhirnya setelah mengeksekusi blok catch.

Referensi