Readable Code in Kotlin

Readable Code in Kotlin

5155c9bc5b30d9e2a8fd677695887861?s=128

kaonash

June 27, 2018
Tweet

Transcript

  1. Readable Code in Kotlin Ken Shimizu(@kaonash_)

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

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

    time it would take someone else to understand it.”
  4. 「コードは理解しやすくなければならない」 “You must write code that minimizes the time it

    would take someone else to understand it.”
  5. Easy to understand(理解しやすい) ≠ Concise(簡潔)

  6. How to write “Readable Code”?

  7. Read the book!!!!

  8. THE END

  9. 1. Handling Nullable

  10. Nullable should be cast to non-null as soon as possible.

  11. 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) }
  12. 2. Don’t too dependent to type inferred

  13. Type inferred is very useful val hoge = listof(1, 3,

    5, 7) Type: List<Int> is omittable
  14. 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?
  15. This is more “Readable”! fun func() { val hoge: User

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

    trivial val hoge = “foo” val user = User() ・ Can infer easily from name val connection = createConnection()
  17. Extra. Naming of scoping functions

  18. Do you understand intuitively what ‘let’ means?? hoge?.let{ doSomething(it) }

  19. 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)
  20. Enjoy Kotlin!!

  21. Thank you!!