LoginSignup
2
0

More than 1 year has passed since last update.

Kotlin勉強メモ

Last updated at Posted at 2023-05-22

「Kotlinサーバーサイドプログラミング実践開発」を読んで勉強していく過程で、気付いたことや覚えておきたいことを、後で見返すようにまとめていく。

目次

@ラベル

fun main() {
    val test = listOf("test1", "test2", "test3")

	test.map { it ->
    	if (it == "test2") return
        println(it)
    }

    println("end")
}

上記のコードの実行結果は下記のようになる。

test1

if (it == "test2") returnで一致した場合に return をして、main 関数の処理自体を終わらせてしまっているため、printlen("end")が実行されることもない。

if (it == "test2") returnで一致した処理のみを終了して、次からのループ処理は実行したいという場合には、@ラベルを使って下記のように書く。

fun main() {
    val test = listOf("test1", "test2", "test3")

	test.map { it ->
    	if (it == "test2") return@map
        println(it)
    }

    println("end")
}
test1
test3
end

非同期処理まとめ

通常の同期処理

fun main() {
	println("test1")
    println("test2")
}
test1
test2

launch で非同期処理

fun main() {
	GlobalScope.launch{
        delay(1000L)
        println("test1")
    }
	println("test2")
}
test2

println("test1")の処理が 1 秒待機している間に、println("test2")が実行されて処理が終わってしまうため、test1は出力されない。


runBlocking でスレッドをブロック

fun main() {
    runBlocking{
        delay(1000L)
        println("test1")
    }

	println("test2")
}
test1
test2

runBlocking 内の処理が終わるのを待ってから、println("test2")を実行している。


runBlocking で非同期処理

fun main() {
    runBlocking {
        launch {
            delay(1000L)
            println("test1")
        }

        println("test2")
    }
}
test2
test1

runBlocking でスレッドをブロックしているため、println("test2")が実行された後も処理が続きprintln("test1")も問題なく実行される。


runBlocking で非同期処理の中で同期処理

import kotlinx.coroutines.*

fun main() {
    runBlocking {
        val test1 = async {
            delay(2000L) //2秒待機
            "test1" //返り値
        }

        // test1の処理中に非同期的に処理を行う
        println("test2")

        // test1の処理が終わるのを待つ
        val result = test1.await()

        println(result)


        println("test3")

    }

    println("test4")
}
test2
test1
test3
test4

runBlockin 内では基本的に非同期で処理が行われる。
そのため、test1 の処理中に先にprintln("test2")が実行される。
ただし、val result = test1.await()の部分で test1 の処理が終わるのを待っているため(同期処理)、println("test3")が実行されるのは、test1が出力された後になる。


今後も更新予定...
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0