This document provides an introduction to the Kotlin programming language through a workshop series. It discusses key Kotlin concepts like statically typed vs dynamically typed languages, features of Kotlin like being interoperable with Java, and how to write basic Kotlin code like functions, variables, types, loops, and classes. The document includes code snippets and explanations to demonstrate Kotlin syntax and best practices.
8. What is main() ?
fun main() {
print("Hello, world!!!")
}
It tell the program where to start and what to
execute. The program will always start from the
main block
9. Print it out!
> To print the things out, we use print() or println()
// Doesn't automatically break line
print("Hello, ")
print("My name is Joyce!")
// Automatically break line
println("Hello")
println("My name is Joyce")
10. Comment
Two types of comment
● // ...
● /* ...
...*/
// I'm line comment
var hello = "Hello"
/*
* I'm block comment
*/
fun hello() {
print("Hello World!")
}
20. How to output variable in string
fun main() {
var i : Int = 2
println("${i}")
}
● use ${ }, put variable in { }
● If we want to output $, we can use $
21. Arithmetic Operator
var b = 3 - 4
var c = 5 * 2
var d = 5 / 2 // Integer devision, d = 2
var e = 5.0 / 2 // Float devision, e = 2.5
println("$b, $c, $d, $e, $comp")
22. Relational Operator
Commonly seen in if expressions or while loops to tell if the condition(s)
is(are) satisfied
if(a >= b){
//do something
}else{
//do something else
}
== //equals to
!= //not equals to
> //larger than
< //less than
>= //No less than
<= //No larger than
23. Logical Operator: Multiple Conditions
var a = true
var b = true
var c = false
println(!a)
if(a && b)
println("Both of them are ture.")
if(a || c)
println("Either a or c is true.")
Output:
24. Multiple Conditions: when
val x = 1;
when(x) {
1 -> println("x is equal to 1.")
2 -> println("x is equal to 2.")
else -> println("x is neither 1 nor 2.")
}
25. Practice 1 - Question
Given three number, write a program to find out which number is the
maximum number among these three.
var a = 10
var b = 15
var c = 5
b is the biggest number!
26. Practice 1 - Solution
fun main() {
val a = 10
val b = 15
val c = 5
if (a > b && a > c) { // Check a
println("a:${a} is the biggest number")
} else if (b > a && b > c) { // Check b
println("b:${b} is the biggest number")
} else { // Check c
println("c:${c} is the biggest number")
}
}
27. Container
● What is Container?
> A container is a class, a data structure, or an ADT
● Why we need Container?
> To easliy store and use the same type of data.
28. Array
var a_int_array : IntArray = intArrayOf(1, 2, 3)
var b_array = floatArrayOf(1.1f, 2.2f, 3.3f)
-- datatype : [type]Array e.g. DoubleArray
-- Initialize : [type(lowercase)]ArrayOf e.g. doubleArrayOf
All kind of array can be declared by this way, except String
29. Array -- String
var c_string : Array<String> = arrayOf("Hello", "world")
var c_string_2 = arrayOf("HI", "HI")
31. List
● Just like Array, but Read-Only
// MUST use val only
val list1 = listOf(5, 6, 7, 8)
val list2: List<Int> = listOf(1, 2, 3)
val list3: List<Int> = listOf<Int>()
val list4: listOf<Double>()
32. Set
● Without order
● Elements won’t be repeated
var set1 = setOf(5, 6, 7, 8)
val set2: Set<Int> = setOf(1, 2, 3)
val set3: Set<Int> = setOf<Int>()
33. Map
● Just like dict() in Python
● Access “value” by “key” (“key” must be different)
● Key to value
val map1 = mapOf("a" to "boy", "b" to "girl")
val map2: Map<String, Int> = mapOf("boy" to 1, "girl" to 2)
34. Mutable datatype
● MutableList
● MutableSet
● MutableMap
Think : If we want to change the elements?
Commonly used
● add (add new element)
● remove (remove element)
35. MutableList
● Like list, but can be mutable
var mutablelist: MutableList<Int> = mutableListOf()
mutablelist.add(5) // add data
mutablelist.remove(5) // remove data (use element)
mutablelist.remove(mutablelist[1]) // remove data (use index)
mutablelist.clear() // delete all data
36. MutableSet
● Like set, but can be mutable
var mutableset: MutableSet<Int> = mutableSetOf()
mutableset.add(5) // add data
mutableset.remove(5) // remove data
//Determine whether the element is contained in the Set
println(mutableset.contains(6)) // true
mutableset.clear() // delete all data
37. MutableMap
● Like map, but can be mutable
var mutablemap: MutableMap<String, String> = mutableMapOf()
mutablemap.put("a", "boy") //add data
mutablemap.put("b", "girl") //add data
mutablemap.remove("a") //remove data
mutablemap.clear() //delete all data
39. For Loop
● in a .. b : a increases to b(included))
● in a .. b step c : a increses to b(included) with step c
● in a until b : a increases to b(not included)
● in a downTo b : a decreases to b(included)
for(i in 1..6) { print(i) // 123456}
for(i in 1..6 step 2){ print(i) // 135}
for(i in 1 until 6){ print(i) // 12345}
for(i in 6 downTo 1) { print(i) // 654321}
40. While Loop
● If the condition is False, jump out of the loop.
var count = 0
while(count < 5) {
count++
}
41. Break
● When the condition is Ture, break the loop.
● Can use flag to assign where we want to go to after breaking the loop.
var i = 0; var j = 0
flag@ while(i < 10) {
while(j < 10) {
if(i == 5 && j == 5) {
break@flag
}
j++ }
i++ }
42. Continue
● If the condition is True, go to the beginning of the loop directly.
for(i in 1..5) {
if(i == 3) continue
print(i)
}
Output : 1245
43. Reuse the code - 1
> We need to write things that print lots of information
println("Your name is ${name}")
println("Your phone is ${phone}")
println("Your age is ${age}")
...
println("Your name is ${name}")
println("Your phone is ${phone}")
println("Your age is ${age}")
...
println("Your name is ${name}")
println("Your phone is ${phone}")
println("Your age is ${age}")
44. Reuse the code - 2
> Pack the code in the block! -> Function
block_for_information {
println("Your name is ${name}")
println("Your phone is ${phone}")
println("Your age is ${age}")
}
45. Function
● Need to be independent
● It means function can’t be declare in main() or another fun()
fun fun_name(parameter:datatype=default):return_type {
...
}
fun multi(a: Int, b: Int = 1): Int{
return a * b
}
46. Inline Function
● If the code is short, we can use inline function.
● It doesn’t matter if the return type is not written.
fun multi(a: Int, b: Int = 1): Int = a * b
47. Function Call
fun multi(a: Int, b : Int = 1): Int = a * b
fun main() {
multi(3,5) // automatically in order
multi(b = 3, a = 5) // use specify parameters
}
48. Practice 2 - Question
Write a function to find the factorial of any number. (Suppose it
won’t overflow)
49. Practice 2 - Solution
fun factorial_loop(num: Int): Int {
// Set the result and counter
var res = 1
var count = 1;
// Mutliply the counter until bigger then num
while (count <= num) {
res *= count
count += 1
}
// Return result
return res;
}
50. ● MAINTAINABILITY
where to look for legacy code
● REUSABILITY
reuse code in new systems.
● SCALABILITY
citizen -> student -> NCTU student
Class - Why?
51. ● Must add datatype
Class - Variable
class Data {
var id : String = ""
var gender : String = "boy" // Default gender is boy.
}
fun main() {
val customer = Data()
customer.id = "no.12" // Default “.” to access the member
customer.gender = "girl"
}
52. ● The first letter of class name should be capitaized.(generally)
Class - Function
class Calculate {
fun plus(x : Int, y : Int) : Int = x + y
fun sub(x : Int, y : Int) : Int = x - y
fun multi(x : Int, y : Int) : Int = x * y
fun div(x: Float, y : Float) : Float = x / y
}
53. ● init { }
● We can create what we need
Class - Initialization - 1
class Test(test: Int) {
// Should init the type of the instances
var test_num: Int
// Run immediately after building class
init {
println("Here is the init block.")
test_num = test
}
}
54. ● Instead using init to initialize the object, we can use bracket instead
● Other things still should be done in init block
Class - Initialization - 2
class Test (var test_num: Int) {
// Run immediately after building class
init { println("Here is the init block.") }
}
fun main() {
// Init the object
var test_2 = Test(2)
println(test_2.test_num)
}
55. ● Compare to the original class, Data class emphasizes more about saving data.
● Provide your classes with built-in functions to get value and more.
Special Class - Data Class
56. // Data class
data class User(val name: String,val i:Int, val id: Int)
fun main() {
val user = User("Alex",10, 1)
println(user)
println("name = ${user.component1()}")
println("id = ${user.component3()}")
}
Special Class - data Class
/* Data Class Info
* User(name=Alex, i=10, id=1)
* name = Alex
* id = 1
*/
57. Practice 3 - Question
fun main() {
var complex1 = Complex(2, 3)
var complex2 = Complex(2, 3)
complex1.print() // Print complex number
complex1.add(3, 4) // Add two complex number
complex1.print() // Print complex number
complex2.sub(3, 4) // Subtract two complex number
complex2.print() // Print complex number
}
Use class Complex which contanis print( ), add( ), sub( )
1. print( ) : print real number + imaginary number
2. add( ) : add real part and imaginary part
3. sub( ) : substract real part and imaginary part
58. Practice 3 - Complex number - 1
a + bi
Real
part
Imaginary
part
59. Practice 3 - Complex number - 2
2 + 3i
3 + 4i
+ = 5 + 7i
60. Practice 3 - Complex number - 3
2 + 3i
3 + 4i
- = -1 + -1i
61. Practice 3 - Solution
class Complex(var real: Int, var img: Int) {
fun add(add_real: Int, add_img: Int) {
real += add_real
img += add_img
}
fun sub(add_real: Int, add_img: Int) {
real -= add_real
img -= add_img
}
fun print() {
if (real == 0) {
println("${img}i")
} else if (img > 0) {
println("${real}+${img}i")
} else if (img < 0) {
println("${real}${img}i")
} else {
println("${real}")
}
}