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

Mapped TypeとPlatform Typeの話

RyotaMurohoshi
December 13, 2016

Mapped TypeとPlatform Typeの話

2016/12/13(火)のSansanさんで開催された第4回 Kotlin Sansan勉強会での発表資料です。

RyotaMurohoshi

December 13, 2016
Tweet

More Decks by RyotaMurohoshi

Other Decks in Technology

Transcript

  1. // OK val message : String? = loadMessage() // ίϯύΠϧΤϥʔ

    val message : String = loadMessage() // Nullableܕ͸?.Ͱͳ͍ͱϝϯόΞΫηεͰ͖ͳ͍ // ΋͠message͕nullͳΒmessage?.length΋null println(message?.length) // ίϯύΠϧΤϥʔ println(message.length)
  2. Kotlinͷίʔυ // IDEͩͱʮString!ʯͬͯදࣔ͞ΕΔ Platform Type val message = Utility.loadMessage() //

    String?ܕʹɻString!͸String?ʹ΋୅ೖՄ val message : String? = Utility.loadMessage() // StringܕʹɻString!͸Stringʹ΋୅ೖՄ val message : String = Utility.loadMessage()
  3. NullPointerExcep/onʹͳΔྫ // String!ܕ val message = Utility.loadMessage() // Platform TypeͷString!ܕͷϝϯόʹΞΫηεͨ࣌͠ɺ

    // ͦͷΦϒδΣΫτ͕nullͩͬͨΒNullPointerException println(message.length) // ͜ΕͳΒOKɻnullʹͳΔ println(message?.length)
  4. Javaͷίʔυ public class JInts { public static Integer getWrapperInteger() {

    return /*ུ*/; } @Nullable public static Integer getWrapperIntegerNullable() { return /*ུ*/; } @NotNull public static Integer getWrapperIntegerNotNull() { return /*ུ*/; } }
  5. Kotlinͷίʔυ // num͸Platform TypeͷInt!ܕ val num = JInts.getWrapperInteger() // num͸Int?ܕ

    val num = JInts.getWrapperIntegerNullable() // num͸Intܕ val num = JInts.getWrapperIntegerNotNull()
  6. Kotlinͷίʔυ class KInts { companion object { @JvmStatic fun getInt():

    Int = 0 @JvmStatic fun getNullableInt(): Int? = 0 } }
  7. Javaͷίʔυ public class KIntsUsage { public static void main(String[] args)

    { int num0 = KInts.getInt(); Integer num1 = KInts.getNullableInt(); // ΞϯϘΫγϯάͰ͜͏΋͔͚Δ int num2 = KInts.getNullableInt(); } }
  8. Kotlinͷίʔυ class KLists { companion object { @JvmStatic fun getStringList():

    List<String> = listOf("") @JvmStatic fun getMutableStringList(): MutableList<String> = mutableListOf("") } }
  9. @ReadOnlyͱ@MutableΛ෇༩ͨ͠Javaͷίʔυ(@NotNull΋) public class JLists { @NotNull @ReadOnly public static List<String>

    getReadonlyList() { return new ArrayList<>(); } @NotNull @Mutable public static List<String> getMutableList() { return new ArrayList<>(); } }
  10. Kotlinͷίʔυ // kotlin.collections.List<String!> val list = JLists.getReadonlyList() // ͜Ε΋OK val

    list : List<String> = JLists.getReadonlyList() // ίϯύΠϧΤϥʔ val list : MutableList<String> = JLists.getReadonlyList() println(list.count()) // OK list.clear() // ίϯύΠϧΤϥʔ @ReadOnlyͱ@MutableΛ͚ͭΔ͜ͱͰมԽ
  11. // kotlin.collections.MutableList<String!> val list = JLists.getMutableList() // ͜Ε΋OK val list

    : MutableList<String> = JLists.getMutableList() println(list.count()) // OK list.clear() // OK // MutableList͸ListΛܧঝ͍ͯ͠ΔͷͰɺͭ͡͸͜Ε΋OK // ͨͩclearͱ͔add͸ݺ΂ͳ͍ // val list : List<String> = JLists.getMutableList() @ReadOnlyͱ@MutableΛ͚ͭΔ͜ͱͰมԽ