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

かゆいところに手が届くKotlin

mattak
October 08, 2015

 かゆいところに手が届くKotlin

Kotlin's 8 tips.

mattak

October 08, 2015
Tweet

More Decks by mattak

Other Decks in Technology

Transcript

  1. class Person( val firstName: String, val lastName: String ) {

    val fullName by lazy { “${firstName}, ${lastName}” } } // ͜ͷ࣌఺Ͱ͸ fullName͸ͭ͘ΒΕͳ͍ val person = Person(“John”, “Due”) // ΞΫηεͯ͠ॳΊͯ࡞੒͞ΕΔ println(person.fullName)
  2. // ී௨ͷॻ͖ํ var name: String? = “Kana” var message: String

    = if (name!=null) “Hello, ${name}!” else “Hello.” // let+null coalescing op var name: String? = “Kana” var message: String = name?.let { “Hello, ${it}!” } ?: “Hello.”
  3. // ී௨ͷॻ͖ํ javaClass<Sample>() // M13Ҏ߱ͷॻ͖ํ Sample::class.java // ࢖͍υίϩɺ(TPOύʔε͢Δͱ͖ͳͲ val gson

    = Gson() val person = gson.fromJson(“{\”name\”: \”Ocelot\”}”, Person::class.java)
  4. // Computed properties class Duration(val interval: Long) { var seconds:

    Double get() = interval.toDouble() / 1000 set(value) { this.interval = value * 1000 } } // javaͷsetter/getter͕KotlinͩͱpropertyʹͳΔΑ person.name = “John” // person.setName(String name) person.name // person.getName()
  5. // java class Singleton { private static Singleton instance =

    null; public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } // kotlin object Singleton() // Object͸lazy. ॳճΞΫηεͰOFX͞ΕΔ Singleton
  6. // java class NotSingleton { public static void callClassMethod() {}

    } NotSingleton.callClassMethod(); // kotlin class NotSingleton { companion object { fun callClassMethod() {} } } NotSingleton.callClassMethod()
  7. class A { inner class B { fun doit() {

    val a = this@A // instance of class A val b = this@B // instance of class B } } }
  8. public open class UpdateModel { // ΠϕϯτΛૹ৴͍͚ͨ͠Ͳɺແҙຯͳ஋ΛૹΓ͍ͨ࣌ͱ͔ val updateEvent by

    lazy { BehaviorSubject.create<Unit>() } fun update() { // Unit͸ Object. ৽͍͠instanceΛͭ͘Βͳ͍ updateEvent.onNext(Unit) } }
  9. // طଘͷΫϥεΛ֦ுग़དྷΔ fun <T> Observable<T?>.notNulls(): Observable<T> { return this.filter {

    it != null }. map { it!! } } // ΑΓγϯϓϧʹʂ val observable = Observable.just<Int?>(1, null, 2, null) val normal = observable.filter { it != null }. map { it !! } val pretty = observable.notNulls()