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

Readable Code in Kotlin

Readable Code in Kotlin

kaonash

June 27, 2018
Tweet

More Decks by kaonash

Other Decks in Programming

Transcript

  1. Self Introduction Ken Shimizu(@kaonash_) ・ Server Side Engineer ・ My

    Dream: Immigrate to Nagano  → I bought a land last year. ・ Favorit: Kotlin & KitKat & waterfalls
  2. Readable Code “You need to write code that minimizes the

    time it would take someone else to understand it.”
  3. Which is “readable” to you? fun hoge(foo: String?): String {

    val bar = funcA() return foo?.let { foo -> funcB(foo, bar) } ?: "" } fun hoge(foo: String?): String { foo ?: return "" val bar = funcA() return funcB(foo, bar) }
  4. Type inferred is very useful val hoge = listof(1, 3,

    5, 7) Type: List<Int> is omittable
  5. However, if used too much... fun func() { val hoge

    = doSomething() println(hoge.name) } fun doSomething() = doSomething2() fun doSomething2() = doSomething3() …. fun doSomething10() = User() What type is this?
  6. This is more “Readable”! fun func() { val hoge: User

    = doSomething() println(hoge.name) } fun doSomething() = doSomething2() fun doSomething2() = doSomething3() …. fun doSomething10() = User()
  7. When should I use type inferred? ・ The type is

    trivial val hoge = “foo” val user = User() ・ Can infer easily from name val connection = createConnection()
  8. I think this is better... public inline fun <T, R>

    T.let(f: (T) -> R): R = f(this) public inline fun <T, R> T.run(f: T.() -> R): R = f() public inline fun <T, R> T.map(f: (T) -> R): R = f(this) public inline fun <T> T.run(f: (T) -> Unit) = f(this)