10
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Kotlinで空文字列とNullを相互変換する

Last updated at Posted at 2021-02-12

運用都合で空文字列とNullを相互に変換して取り扱う必要があったので、簡単に備忘録としてまとめておく。

空文字列を受け取ったらNullに変換する

val empty: String = ""
val nullable: String? = empty.ifEmpty { null }

空文字列 or 空白文字列を受け取ったらNullに変換する

val blank: String = " "
val nullable: String? = blank.ifBlank { null }

Nullを受け取ったら空文字列に変換する

val nullable: String? = null
val empty: String = nullable.orEmpty()

動作確認

Kotlin Playgroundでサクッと動作確認。

fun main() {
    listOf("", " ", null, "hoge").forEach { string ->
        check(string)

        print("string.orEmpty()        : ")
        check(string.orEmpty())

        print("string?.ifEmpty{ null } : ")
        check(string?.ifEmpty{ null })

        print("string?.ifBlank{ null } : ")
        check(string?.ifBlank{ null })

        println("")
    }
}

fun check(string: String?) {
    when(string) {
        null -> println("null")
        ""   -> println("empty")
        " "  -> println("blank")
        else -> println(string)
    }
}
empty
string.orEmpty()        : empty
string?.ifEmpty{ null } : null
string?.ifBlank{ null } : null

blank
string.orEmpty()        : blank
string?.ifEmpty{ null } : blank
string?.ifBlank{ null } : null

null
string.orEmpty()        : empty
string?.ifEmpty{ null } : null
string?.ifBlank{ null } : null

hoge
string.orEmpty()        : hoge
string?.ifEmpty{ null } : hoge
string?.ifBlank{ null } : hoge
10
5
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
10
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?