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

Kotlin - #渋谷JVM

Kotlin - #渋谷JVM

渋谷JVMの懇親会LT用のスライドです。Kotlinの拡張関数とNULL安全について簡単に紹介します。

Taro Nagasawa

April 18, 2015
Tweet

More Decks by Taro Nagasawa

Other Decks in Programming

Transcript

  1. fun main(args : Array<String>) { "world".hello() / / => Hello,

    world! } ! fun String.hello() { println("Hello, ${this}!") }
  2. / / Kotlin fun String.hello() { println("Hello, ${this}!") } !

    / / Java static void hello(String receiver) {...}
  3. val a: String = null / / NG val b:

    String? = null / / OK /PU/VMM/VMMBCMF Λ໌֬ʹ۠ผ͢Δ
  4. val a: String? = null a ?: "" / /

    a.orElse(""); ͰσϑΥϧτ஋
  5. val a: String? = null a!! / / !!!Exception!!! /

    / a.get(); Ͱڧ੍/PU/VMMԽ ةݥʂݪଇېࢭʂ
  6. w JG1SFTFOU w NBQ w qBU.BQ ,PUMJOʹ͸WPJE ͸ͳ͘ɺؔ਺͸ ඞͣ஋Λฦ͔͢ Βಉ͡

    ֦ுؔ਺MFU͸໾͜ͳ͢ MFU͸ඪ४ϥΠϒϥϦͷؔ਺
  7. a?.let { a -> toInt(a) } a?.let { toInt(it) }

    a?.let(::toInt) MFU࢖༻ྫ ಉ͡ɻ ॻ͖ํ͕ҧ ͏͚ͩ
  8. a?.let { a -> b?.let { b -> a -

    b } } ͭͷ*OU B CͷҾ͖ࢉ
  9. a?.let { a -> b?.let { b -> a -

    b } } ͭͷ*OU B CͷҾ͖ࢉ ωετ ಡΈʹ͍͘
  10. / / Ҿ͖ࢉͷؔ਺ ΧϦʔԽ val minus = fun(a: Int) =

    fun(b: Int) = a - b ! Ҿ਺ͱͯ͠/VMMBCMFͳؔ਺ΛऔΕΔMFUతͳ΍ͭ fun <A, B> A.bind(f: ((A) -> B)?): B? = f?.invoke(this) ͭͷؔ਺Λ༻ҙ
  11. ෳࡶ ໘౗͍͘͞ val minus = fun(a: Int) = fun(b: Int)

    = a - b fun <A, B> A.bind(f: ((A) -> B)?): B? = f?.invoke(this) fun <A, B> ((A)->B).apply(a: A?): B? = a?.bind(this)
  12. if (a != null && b != null) a -

    b else null ࣮͸͜Ε͚ͩͰ͓̺