KOTLIN
Introduction
1
KOTLIN : Basic Information
● Cross-platform, statically typed, general-purpose programming language.
● Interopate fully with Java & complains with JVM.
● Mainly targets JVM, but compiles to Javascript.
● Inspired by :
● Java
● C#
● JavaScript
● Scala
● Groovy
2
KOTLIN : Basic Information
● Developed by : JetBrains (Roman Elizarov is the current lead language
designer).
● Developed under Apache license 2.0, as an open source language.
● Object - oriented & Functional constructs.
● Easy to learn language
● .kt,.kts,.ktm (extensions)
3
KOTLIN : Usage
● General-purpose programming language
● Server-side & Client-side development.
● Desktop programs development.
● Mobile apps development. ( cross-platform development)
4
KOTLIN : Timeline
• July 2011 : JetBrains exposes project Kotlin with its lead developer being Dmitry
Jemerov.
• February 2012 : Kotlin becomes an open source project.
• February 2016 : Kotlin official release v1.0
• 2017 : Google announced first-class support for Kotlin on Android.
• Kotlin 1.2 was released on November 28, 2017. Sharing code between JVM and
JavaScript platforms feature was newly added to this release (multiplatform
programming is by now a beta feature upgraded from "experimental"). A full-stack
demo has been made with the new Kotlin/JS Gradle Plugin.
• Kotlin 1.3 was released on 29 October 2018, bringing coroutines for asynchronous
programming.
5
KOTLIN : Timeline
• On 7 May 2019, Google announced that the Kotlin programming language is
now its preferred language for Android app developers.
• Kotlin 1.4 was released in August 2020, with e.g. some slight changes to the
support for Apple's platforms, i.e. to the Objective-C/Swift interop.
• Kotlin 1.5 was released in May 2021.
• Kotlin 1.6 was released in November 2021.
• Kotlin 1.7 was released in June 2022, including the alpha version of the new
Kotlin K2 compiler.
• Kotlin 1.8 was released in December 2022, 1.8.0 was released on January
11, 2023.
• Kotlin 1.9 was released in July 2023, 1.9.0 was released on July 6, 2023.
6
KOTLIN vs Java
● Kotlin Application Deployment is faster, lightweight & prevents applications
from increasing size.
● Kotlin is less verbose and more concise.
● Kotlin is more type-safe, and has the feature of smart cast.
● Kotlin has a higher-order functions.
7
Programming : Design
● Designed to be an industrial-strength object-oriented language.
● According to Kotlin developers, you can call JavaScript code from Kotlin
● Generate libraries that can be consumed as modules.
● JVM version of Kotlin standard library depends on Java Class Library.
8
Programming : Syntax
● Like in C, C++, C#, Java, and Go, the entry point to a Kotlin program is a
function named "main", which may be passed an array containing any
command-line arguments.
9
Package definition and imports
● Package specification should be at the top of the source file.
10
11
12
13
Cú pháp khai báo biến (variable)
var tên_biến : Kiểu_Dữ_Liệu = Giá_Trị_Mặc_Định
Ví dụ :
var x : Long = 100L
var y : Double = 113.5
var f : Float = 13.5f
var i : Int = 113
var s : Short = 8
var b : Byte = 1
var c : Char = „c‟
var ten : String = “PTIT”
var kq : Boolean = true
14
15
Cú pháp khai báo hằng
Khi khai báo hằng số dùng val thay vì var (var cho phép thay đổi giá
trị của biến, còn val không cho phép)
Cú pháp:
var tên_hằng : Kiểu_Dữ_Liệu = Giá_Trị_Hằng
Ví dụ:
val PI : Double =3.14
PI=3.15 //không được phép vì PI là readonly
16
Ép kiểu dữ liệu trong Kotlin Trong Kotlin, bất kỳ kiểu dữ liệu number
nào cũng có sẵn các phương thức :
toByte(): Byte
toShort(): Short
Ví dụ : toInt(): Int
var s : Short = 8 toLong(): Long
var X : Int=10 toFloat(): Float
var D : Double = X.toDouble() toDouble(): Double
println("X = "+X) toChar(): Char
println("D = "+D)
var F : Double = 10.5
var Y : Int = F.toInt()
println("F = "+F)
println("Y = "+Y)
var t = 13L+1
println(t)
17
Nhập dữ liệu
Nhập dữ liệu từ bàn phím ta dùng hàm readLine(), hàm này nằm trong thư
viện mặc định kotlin.io
Hàm readLine() sẽ trả về một chuỗi dữ liệu được nhập vào từ bàn phím
hoặc là giá trị null nếu như không có dữ liệu.
Từ chuỗi kết quả này ta có thể ép kiểu dữ liệu về bất kỳ kiểu nào
Ví dụ :
fun main(args: Array) {
println(“Hãy nhập tên bạn: ”)
var ten:String ?= readLine()
println(“Tên bạn là: ”)
println(ten)
} 18
19
20
Conditions
21
Conditions
22
Conditions
23
Conditions
24
Loops
25
Loops
26
Loops
27
Ví dụ: Viết chương trình tính 5 giai thừa
fun main(args: Array) {
Loops var n:Int = 5
var gt:Int=1
var i:Int = 1
do {
gt *= i
i++
}while (i<=n)
println("$n! =$gt")
}
28
Loops
29
Loops
30
Loops
31
Cú pháp khai báo mảng (array)
var Tên_Mảng : Kiểu_Dữ_Liệu_Mảng = XXXArrayOf(giá trị 1, giá trị 2,…, giá trị n)
Ví dụ :
var arrX : IntArray= intArrayOf(1,2,3,5)
println(arrX[1])
var arrY : DoubleArray= doubleArrayOf(1.5,2.6,9.0,10.3)
println(arrY[3])
var arrC : CharArray= charArrayOf('a','b','c')
println(arrC[0])
32
Cú pháp thao tác mảng (array)
var Tên_Mảng :
Kiểu_Dữ_Liệu_Mảng =
Kiểu_Dữ_Liệu_Mảng (Số
phần tử n)
Ví dụ :
var M :IntArray= IntArray(n)
33
Cú pháp mảng (array)
Ví dụ :
var M:IntArray= IntArray(10)
Nhập giá trị cho từng phần tử trong mảng M:
M[0]=100
M[1]=20
var x:Int=M[2]
for (i in M.indices)
print(“${M[i]}\t”)
hoặc duyệt giá trị theo cách:
for (i in M)
print(“$i\t”)
34
Mảng 2 chiều (2D-Array)
35
Cú pháp mảng 2 chiều:
Ví dụ :
Để nhập liệu cho các phần tử trong mảng 2 chiều M:
var rd:Random = Random()
for(i in M.indices) {
for(j in M[i].indices) {
M[i][j]=rd.nextInt(100)
}
}
Để xuất dữ liệu ra màn hình:
for(i in M.indices) {
for(j in M[i].indices) {
print(“${M[i][j]}\t”)
}
println()
} 36
Xử lý ngoại lệ
Cú pháp:
Ví dụ:
try {
// viết lệnh ở đây và các lệnh này có khả fun chia(a:Int, b:Int):Int {
// năng sinh ra lỗi if (b==0)
} throw Exception("Mẫu số =0")
catch (e: SomeException) { return a/b
// handler lỗi ở đây -> thông báo lỗi chi tiết }
// để biết mà sửa cái gì fun main(args: Array) {
} try {
finally { chia(5, 0)
// optional finally block – cho dù có lỗi hay } catch (e:Exception) {
// không có lỗi xảy ra thì luôn thực hiện println(e.message)
} }
println("Cám ơn!")
}
37
Collection trong Kotlin
38
Collection trong Kotlin
39
● Extended Functions :
Kotlin adds the concept of an extension function which allows a function to be
"glued" onto the public function list of any class without being formally placed
inside of the class.
● Unpacking arguments
Similar to Python, the spread operator asterisk (*) unpacks an array's contents as
comma-separated arguments to a function :
40
Null Safety
● Kotlin makes a distinction between nullable and non-nullable data types.
● All nullable objects must be declared with a "?" postfix after the type name.
● Operations on nullable objects need special care from developers.
● Kotlin provides null-safe operators to help developers :
- “?.” (safe navigation operator)
- “? : ” (null coalescing operator) often referred to as the Elvis operator.
41
Small syntax properties of KOTLIN
● Classes are final by default
● Abstract classes are open by default (overridable)
● Classes are public by default
● Primary and secondary constructors
42
Features of KOTLIN
● Kotlin interactive shell
● Kotlin as a scripting language
43
Modern Applications of KOTLIN :
● When Kotlin was announced as an official Android development language it became the third
language fully supported for Android, in addition to Java and C++.
● As of 2020, Kotlin is still most widely used on Android, with Google estimating that 70% of the
top 1000 apps on the Play Store are written in Kotlin. Google itself has 60 apps written in
Kotlin, including Maps and Drive.
● Kotlin on Android is seen as beneficial for its null-pointer safety as well as for its features that
make for shorter, more readable code.
● In addition to its prominent use on Android, Kotlin is gaining traction in server-side
development.
● From a survey of developers who use Kotlin, that 56% were using it for mobile apps, while
47% were using it for a web back-end.
● Most Kotlin users were targeting Android (or otherwise on the JVM).
44
Companies that use KOTLIN
45
46