Upgrade to Pro — share decks privately, control downloads, hide ads and more …

プラットホーム型について ~Kotlinだって間違えるとnullでハマるよ!~

プラットホーム型について ~Kotlinだって間違えるとnullでハマるよ!~

2017/07/24

『2017年7月定例会「Kotlin & Android Studio 3.0」』

の発表資料です

RyotaMurohoshi

July 24, 2017
Tweet

More Decks by RyotaMurohoshi

Other Decks in Technology

Transcript

  1. val message: String? = readMessage() // ࣍͸ίϯύΠϧΤϥʔ // String?ͰJavaΈ͍ͨͳॻ͖ํ͸Ͱ͖ͳ͍ val

    messageLength: Int = message.length // ࣍͸ίϯύΠϧΤϥʔʹ͸ͳΒͳ͍͕ // message͕nullͳΒ͹ϥϯλΠϜΤϥʔ val messageLength: Int = message!!.length // ࣍͸OK // messageLength͸IntܕͰͳ͘Int?ܕ val messageLength: Int? = message?.length
  2. Kotlin͔Βݺͼग़͢ͱɻɻɻ // ͜Ε͸ίϯύΠϧΤϥʔʹͳΒͳ͍ val str = Reader.readNullableStringJava() // ͜Ε΋ίϯύΠϧΤϥʔʹͳΒͳ͍ val

    str : String? = Reader.readNullableStringJava() // ஫໨ʂ͜Ε΋ίϯύΠϧΤϥʔʹͳΒͳ͍ʂʂʂ val str : String = Reader.readNullableStringJava()
  3. ʲ࠶ܝʳKotlin͔Βݺͼग़͢ͱɻɻɻ // ͜Ε͸ίϯύΠϧΤϥʔʹͳΒͳ͍ val str = Reader.readNullableStringJava() // ͜Ε΋ίϯύΠϧΤϥʔʹͳΒͳ͍ val

    str : String? = Reader.readNullableStringJava() // ஫໨ʂ͜Ε΋ίϯύΠϧΤϥʔʹͳΒͳ͍ʂʂʂ val str : String = Reader.readNullableStringJava()
  4. Javaͷίʔυ public class Reader { public static String readNullableStringJava() {

    return null; } } Kotlinͷίʔυ // ͜ͷ୅ೖͨ͋ͨ͠ΓͰIllegalStateExceptionൃੜ val str : String = Reader.readNullableStringJava()
  5. Javaͷίʔυ public class Reader { public static String readNullableStringJava() {

    return null; } } Kotlinͷίʔυ // ͜ͷ୅ೖΛͨ͋ͨ͠ΓͰ͸ϥϯλΠϜΤϥʔ͸ൃੜ͠ͳ͍ val str = Reader.readNullableStringJava() // ͜͜ͰNullPointerExceptionͰࢮ͵ val length = str.length
  6. Kotlin͔Βݺͼग़͢ͱɻɻɻ // Լͷstr͸ϓϥοτϗʔϜܕͷString! // ͚ͲString!ͬͯ໌ࣔతʹ͸ॻ͚ͳ͍ val str = Reader.readNullableStringJava() //

    String?ܕͷม਺ʹ୅ೖ val str : String? = Reader.readNullableStringJava() // Stringܕͷม਺ʹ୅ೖ val str : String = Reader.readNullableStringJava()
  7. ͦͷ2ɹString?ܕ // Լ͸Stringܕ val str: String? = Reader.readNullableStringJava() // OK

    println(str?.length) // ίϯύΠϧΤϥʔ println(str.length)
  8. ͦͷ3ɹStringܕ // Լ͸Stringܕ // ίϯύΠϧΤϥʔʹ͸ͳΒͳ͍ // ୅ೖͨ͋ͨ͠ΓͰIllegalStateException͕ൃੜ val str: String

    = Reader.readNullableStringJava() // ͦΕඞཁͳ͍Αͬͯɺܯࠂ͕ग़Δ println(str?.length) // OK println(str.length)
  9. // IDE͕ɺฦΓ஋ܕ͸Stringͬͯڭ͑ͯ͘ΕΔʢString!Ͱ͸ͳ͍ʣ val str = Reader.readNotNull() // ͜Ε΋OK val str

    : String = Reader.readNotNull() // ࣮͸ɺ͜Ε΋OK val str : String? = Reader.readNotNull()
  10. // IDE͕ɺฦΓ஋ܕ͸String?ͬͯڭ͑ͯ͘ΕΔʢString!Ͱ͸ͳ͍ʣ val str = Reader.readNullable() // ͜Ε΋OK val str

    : String? = Reader.readNullable() // ͜Ε͸ίϯύΠϧΤϥʔ val str : String = Reader.readNullable()