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

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

2017/07/24

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

の発表資料です

F46c97bb74758d481531990654933050?s=128

RyotaMurohoshi

July 24, 2017
Tweet

Transcript

  1. 27.
  2. 31.

    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
  3. 34.
  4. 42.
  5. 46.

    Kotlin͔Βݺͼग़͢ͱɻɻɻ // ͜Ε͸ίϯύΠϧΤϥʔʹͳΒͳ͍ val str = Reader.readNullableStringJava() // ͜Ε΋ίϯύΠϧΤϥʔʹͳΒͳ͍ val

    str : String? = Reader.readNullableStringJava() // ஫໨ʂ͜Ε΋ίϯύΠϧΤϥʔʹͳΒͳ͍ʂʂʂ val str : String = Reader.readNullableStringJava()
  6. 50.

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

    str : String? = Reader.readNullableStringJava() // ஫໨ʂ͜Ε΋ίϯύΠϧΤϥʔʹͳΒͳ͍ʂʂʂ val str : String = Reader.readNullableStringJava()
  7. 52.
  8. 58.

    Javaͷίʔυ public class Reader { public static String readNullableStringJava() {

    return null; } } Kotlinͷίʔυ // ͜ͷ୅ೖͨ͋ͨ͠ΓͰIllegalStateExceptionൃੜ val str : String = Reader.readNullableStringJava()
  9. 61.

    Javaͷίʔυ public class Reader { public static String readNullableStringJava() {

    return null; } } Kotlinͷίʔυ // ͜ͷ୅ೖΛͨ͋ͨ͠ΓͰ͸ϥϯλΠϜΤϥʔ͸ൃੜ͠ͳ͍ val str = Reader.readNullableStringJava() // ͜͜ͰNullPointerExceptionͰࢮ͵ val length = str.length
  10. 69.

    Kotlin͔Βݺͼग़͢ͱɻɻɻ // Լͷstr͸ϓϥοτϗʔϜܕͷString! // ͚ͲString!ͬͯ໌ࣔతʹ͸ॻ͚ͳ͍ val str = Reader.readNullableStringJava() //

    String?ܕͷม਺ʹ୅ೖ val str : String? = Reader.readNullableStringJava() // Stringܕͷม਺ʹ୅ೖ val str : String = Reader.readNullableStringJava()
  11. 72.

    ͦͷ2ɹString?ܕ // Լ͸Stringܕ val str: String? = Reader.readNullableStringJava() // OK

    println(str?.length) // ίϯύΠϧΤϥʔ println(str.length)
  12. 73.

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

    = Reader.readNullableStringJava() // ͦΕඞཁͳ͍Αͬͯɺܯࠂ͕ग़Δ println(str?.length) // OK println(str.length)
  13. 77.
  14. 82.

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

    : String = Reader.readNotNull() // ࣮͸ɺ͜Ε΋OK val str : String? = Reader.readNotNull()
  15. 84.

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

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