Skip to content

Latest commit

 

History

History
298 lines (210 loc) · 5.31 KB

File metadata and controls

298 lines (210 loc) · 5.31 KB
val numLetters = "Hello World".count()
    print(numLetters)
fun main() {
    val numLetters = "Hello World".count( {letter-> letter=='o'})
    // This is like where condition in Java, filter {letter-> letter=='o'}
    // is true, and count the number of true, and the function is't 
    //important.



    print(numLetters)
}
fun main() {
    val numLetters = "Hello World".count( {x-> x=='o'})
    print(numLetters)
}

In this case, the condition is also a function, but regardless the name, or variable, we can also use a named function.

fun main() {
    val numLetters = "Hello World".count(::isO)

// :: mean past the function
    println(numLetters)
}

fun isO(letter: Char): Boolean {
    return letter == 'o'
}
// take out the name, greetingFunction.
fun main() {
println({val currentYear=2023
    "Welcome $currentYear"
    }())
}

// Original 
// LET greetingFunction as a variable, not function, a variable that saves
// function.
fun main() {
    val greetingFunction: ()-> String = {
    val currentYear=2023
    "Welcome $currentYear"
}
    println(greetingFunction())
}

// More basic version
fun main() {
    println(generateGreeting())
}

fun generateGreeting(): String {
    val currentYear = 2023
    return "Welcome $currentYear"
}

If we the function only use once, we can use lambda. so we don't need to declare the function.


$it 隱含為第一個輸入參數

fun main() {
val greetingFunction: (String)-> String = {
    val currentYear=2023
    "Welcome $it. It's $currentYear"
}
    println(greetingFunction("somebody"))
}

Mutiple variable

fun main() {
    val greetingFunction: (String, Int)-> String = { x, currentYear->
        "Welcome $x. It's $currentYear"
    }
        println(greetingFunction("somebody",2023))
    }
        
println(peopleNames.sortedWith { 
            str1: String, str2: String -> str1.length - str2.length 
    })

sortedWith need a function, if the function return negtive, it means that str1 is shorter than str2, so put str1 in the first.

If we use named function:

val byLength = Comparator<String> { s1, s2 ->
    s1.length - s2.length
}
println(peopleNames.sortedWith(byLength))

//Because interface only has one function, so we can use lambda, and it
//will automateical select the only function -> compare.


//JAVA version
Comparator<String> byLength = new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }
};

   

//Functional Interface

interface Comparator<T> {
    fun compare(o1: T, o2: T): Int
}


public fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>): 
List<T>

//sortedWith specifify that it needs to contain a comparator.
//so we need a Comparator.

Compare can be sorted by many ways, If we use Bubble sort, it's kinda like sliding window.

Example:

Sort("amy","Johnson","bob")

First itteration 

"amy" vs "Johnson"

amy is smaller, no change.

"bob" vs "johnson"

bob is smaller, change -> ("amy","bob","johnson")

"bob" vs "amy"

same length, no change.

Cleanest version

println(peopleNames.sortedWith(compareBy { it.length }))

Threads

//java version

val runnable = Runnable {
    println("Running from Runnable")
}
val t = Thread(runnable)
t.start()

Kotlin version

because it only has one interface, so we put thing in it it will automatic change into previous one.

val t = Thread {
    println("Running in a new thread: ${Thread.currentThread().name}")
}
t.start()

// Real case
Thread {
    println("hi")
}.start()

// turn into
Thread(Runnable {
    println("hi")
}).start()

QUESTION:

Why Thread need an runnable, you can't directy put somethings in it?

val task = Runnable { println("doing work") }

val thread1 = Thread(task)
val thread2 = Thread(task) // Can be use mutible times

Thread test:

fun main() {
    val startTime = System.currentTimeMillis()

    doWork("A")
    doWork("B")
    doWork("C")

    val endTime = System.currentTimeMillis()
    println("總共花費時間: ${endTime - startTime} 毫秒")
}

fun doWork(name: String) {
    println("任務 $name 開始")
    Thread.sleep(1000) // 模擬做事 1 秒
    println("任務 $name 結束")
}


任務 A 開始
任務 A 結束
任務 B 開始
任務 B 結束
任務 C 開始
任務 C 結束
總共花費時間:3000 毫秒
fun main() {
    val startTime = System.currentTimeMillis()

    // 建立三個 Runnable 任務
    val taskA = Runnable { doWork("A") }
    val taskB = Runnable { doWork("B") }
    val taskC = Runnable { doWork("C") }

    // 把 Runnable 包進 Thread 執行緒中
    val t1 = Thread(taskA)
    val t2 = Thread(taskB)
    val t3 = Thread(taskC)

    // 啟動所有執行緒
    t1.start()
    t2.start()
    t3.start()

    // 等待所有執行緒做完
    t1.join()
    t2.join()
    t3.join()

    val endTime = System.currentTimeMillis()
    println("總共花費時間: ${endTime - startTime} 毫秒")
}

fun doWork(name: String) {
    println("任務 $name 開始於執行緒:${Thread.currentThread().name}")
    Thread.sleep(1000)
    println("任務 $name 結束")
}