Slide 1

Slide 1 text

Readable Code in Kotlin Ken Shimizu(@kaonash_)

Slide 2

Slide 2 text

Self Introduction Ken Shimizu(@kaonash_) ・ Server Side Engineer ・ My Dream: Immigrate to Nagano  → I bought a land last year. ・ Favorit: Kotlin & KitKat & waterfalls

Slide 3

Slide 3 text

Readable Code “You need to write code that minimizes the time it would take someone else to understand it.”

Slide 4

Slide 4 text

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

Slide 5

Slide 5 text

Easy to understand(理解しやすい) ≠ Concise(簡潔)

Slide 6

Slide 6 text

How to write “Readable Code”?

Slide 7

Slide 7 text

Read the book!!!!

Slide 8

Slide 8 text

THE END

Slide 9

Slide 9 text

1. Handling Nullable

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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) }

Slide 12

Slide 12 text

2. Don’t too dependent to type inferred

Slide 13

Slide 13 text

Type inferred is very useful val hoge = listof(1, 3, 5, 7) Type: List is omittable

Slide 14

Slide 14 text

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?

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

When should I use type inferred? ・ The type is trivial val hoge = “foo” val user = User() ・ Can infer easily from name val connection = createConnection()

Slide 17

Slide 17 text

Extra. Naming of scoping functions

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

I think this is better... public inline fun T.let(f: (T) -> R): R = f(this) public inline fun T.run(f: T.() -> R): R = f() public inline fun T.map(f: (T) -> R): R = f(this) public inline fun T.run(f: (T) -> Unit) = f(this)

Slide 20

Slide 20 text

Enjoy Kotlin!!

Slide 21

Slide 21 text

Thank you!!