SlideShare a Scribd company logo
1 of 63
DSC Workshop Series:
Kotlin 101
Presented by Joyce
FacebookWebsite
Introduction to Kotlin
Kotlin is a statically typed language, objected-
oriented language developed by JetBrains in 2011.
Statically typed language
> The type of the variable should be decide in compile time.
Dynamically Statically
Features of Kotlin
Interoperable with Java
Safe
Concise
FULLFULLSTACK
IDE for Kotlin
Kotlin Playground
Click me to go
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
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")
Comment
Two types of comment
● // ...
● /* ...
...*/
// I'm line comment
var hello = "Hello"
/*
* I'm block comment
*/
fun hello() {
print("Hello World!")
}
Types - category
● Int
● Long
● Char
● Float
● Double
● String
● ...
Types - range
Types - range
To print out the range of the type do :
● println(Int.MAX_VALUE)
● println(Int.MIN_VALUE)
Overflow
fun main() {
var i : Int = 2147483648 // 2^32
}
Assign the variable
> Give a variable a name. We can use it anytime
val a = 10 //constant value
var x = 10 //variable
Declare Variables/Values
a = 9
‘=’ means assign LHS with RHS
Declare Variables/Values
var x = 10 // Int
var y = 10.5 // Float
var b = false //Boolean
var s = "string" //String
val p = 1.11 //Float
Declare Variables/Values : Initalize with type
// Add type after the name
var b : Boolean = false
var s : String = "string"
val p : Float = 1.11
Declare Variables/Values : Type mismatch
var x = 10 // type is Int
x = "str" // Assign String to Int
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 $
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")
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
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:
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.")
}
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!
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")
}
}
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.
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
Array -- String
var c_string : Array<String> = arrayOf("Hello", "world")
var c_string_2 = arrayOf("HI", "HI")
Read-Only datatype
● List
● Set
● Map
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>()
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>()
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)
Mutable datatype
● MutableList
● MutableSet
● MutableMap
Think : If we want to change the elements?
Commonly used
● add (add new element)
● remove (remove element)
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
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
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
● Reusability
reuse your code
● Do things repeatedly (with specific order)
Loop - why
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}
While Loop
● If the condition is False, jump out of the loop.
var count = 0
while(count < 5) {
count++
}
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++ }
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
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}")
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}")
}
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
}
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
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
}
Practice 2 - Question
Write a function to find the factorial of any number. (Suppose it
won’t overflow)
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;
}
● MAINTAINABILITY
where to look for legacy code
● REUSABILITY
reuse code in new systems.
● SCALABILITY
citizen -> student -> NCTU student
Class - Why?
● 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"
}
● 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
}
● 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
}
}
● 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)
}
● 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
// 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
*/
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
Practice 3 - Complex number - 1
a + bi
Real
part
Imaginary
part
Practice 3 - Complex number - 2
2 + 3i
3 + 4i
+ = 5 + 7i
Practice 3 - Complex number - 3
2 + 3i
3 + 4i
- = -1 + -1i
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}")
}
}
Demo time!
Click me!
QA Time~

More Related Content

What's hot

Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
Kamil Toman
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
rohassanie
 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional Architecture
John De Goes
 

What's hot (20)

Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
 
Python The basics
Python   The basicsPython   The basics
Python The basics
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17
 
The best of AltJava is Xtend
The best of AltJava is XtendThe best of AltJava is Xtend
The best of AltJava is Xtend
 
MP in Clojure
MP in ClojureMP in Clojure
MP in Clojure
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!
 
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswiftSwift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional Architecture
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
Talk Code
Talk CodeTalk Code
Talk Code
 
Free Monads Getting Started
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting Started
 

Similar to Kotlin

F# Presentation
F# PresentationF# Presentation
F# Presentation
mrkurt
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
SyedHaroonShah4
 

Similar to Kotlin (20)

01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx
 
Introduction to Kotlin.pptx
Introduction to Kotlin.pptxIntroduction to Kotlin.pptx
Introduction to Kotlin.pptx
 
Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...
 
Day 1
Day 1Day 1
Day 1
 
F# Presentation
F# PresentationF# Presentation
F# Presentation
 
Writing MySQL UDFs
Writing MySQL UDFsWriting MySQL UDFs
Writing MySQL UDFs
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab Manual
 
Groovy
GroovyGroovy
Groovy
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Core C#
Core C#Core C#
Core C#
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
C++ theory
C++ theoryC++ theory
C++ theory
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
 
C++ Boot Camp Part 1
C++ Boot Camp Part 1C++ Boot Camp Part 1
C++ Boot Camp Part 1
 
JSUG - Effective Java Puzzlers by Christoph Pickl
JSUG - Effective Java Puzzlers by Christoph PicklJSUG - Effective Java Puzzlers by Christoph Pickl
JSUG - Effective Java Puzzlers by Christoph Pickl
 
Dart workshop
Dart workshopDart workshop
Dart workshop
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 

Recently uploaded

Recently uploaded (20)

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

Kotlin

  • 1. DSC Workshop Series: Kotlin 101 Presented by Joyce FacebookWebsite
  • 2. Introduction to Kotlin Kotlin is a statically typed language, objected- oriented language developed by JetBrains in 2011.
  • 3. Statically typed language > The type of the variable should be decide in compile time. Dynamically Statically
  • 4. Features of Kotlin Interoperable with Java Safe Concise
  • 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!") }
  • 11. Types - category ● Int ● Long ● Char ● Float ● Double ● String ● ...
  • 13. Types - range To print out the range of the type do : ● println(Int.MAX_VALUE) ● println(Int.MIN_VALUE)
  • 14. Overflow fun main() { var i : Int = 2147483648 // 2^32 }
  • 15. Assign the variable > Give a variable a name. We can use it anytime
  • 16. val a = 10 //constant value var x = 10 //variable Declare Variables/Values a = 9 ‘=’ means assign LHS with RHS
  • 17. Declare Variables/Values var x = 10 // Int var y = 10.5 // Float var b = false //Boolean var s = "string" //String val p = 1.11 //Float
  • 18. Declare Variables/Values : Initalize with type // Add type after the name var b : Boolean = false var s : String = "string" val p : Float = 1.11
  • 19. Declare Variables/Values : Type mismatch var x = 10 // type is Int x = "str" // Assign String to Int
  • 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
  • 38. ● Reusability reuse your code ● Do things repeatedly (with specific order) Loop - why
  • 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}") } }

Editor's Notes

  1. 會讀錯誤訊息很重要
  2. 會讀錯誤訊息很重要