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

8. Conventions [kotlin-workshop]

8. Conventions [kotlin-workshop]

Part of https://github.com/jetBrains/kotlin-workshop.

Covers:
- Operator Overloading
- Other conventions: comparisons, in, iterator, etc.
- Destructuring Declarations
- Delegated Properties (incl. lazy example)

Svetlana Isakova

November 01, 2017
Tweet

More Decks by Svetlana Isakova

Other Decks in Programming

Transcript

  1. plus operator fun Point.plus(other: Point): Point {
 return Point(x +

    other.x, y + other.y)
 } Point(1, 2) + Point(2, 3)
  2. Arithmetic operations expression function name a + b plus a

    - b minus a * b times a / b div a % b mod
  3. No restrictions on parameter type operator fun Point.times(scale: Int): Point

    {
 return Point(x * scale, y * scale)
 } Point(1, 2) * 3
  4. Conventions for lists val list = listOf(1, 2, 3)
 val

    newList = list + 2
 
 val mutableList = mutableListOf(1, 2, 3)
 mutableList += 4
  5. Prefer val to var var list = listOf(1, 2, 3)

    list += 4 list = list + 4 new list is created:
  6. Comparisons symbol translated to a > b a.compareTo(b) > 0

    a < b a.compareTo(b) < 0 a >= b a.compareTo(b) >= 0 a <= b a.compareTo(b) <= 0
  7. The rangeTo convention if (s in "abc".."def") { }
 for

    (i in 1..2) { }
 
 val oneTo100: IntRange = 1..100
 for (i in oneTo100) { }
  8. Destructuring in lambdas val map = mapOf(1 to "one", 2

    to "two") map.mapValues { (key, value) -> "$key -> $value!" } map.mapValues { (_, value) -> "$value!" }
  9. Lazy property val lazyValue: String by lazy {
 println("computed!")
 "Hello"


    }
 
 fun main(args: Array<String>) {
 println(lazyValue)
 println(lazyValue)
 } computed! Hello Hello
  10. Delegated properties class C {
 private val delegate = Delegate()


    var prop: Type
 set(value: Type) = delegate.setValue(..., value)
 get() = delegate.getValue(...)
 }
  11. object Users : IdTable() { val name = varchar("name", length

    = 50).index() val age = integer("age") } class User(id: EntityID) : Entity(id) { var name: String by Users.name var age: Int by Users.age } Delegated properties in frameworks corresponds to a table in the database corresponds to a specific entry in this table columns values
  12. object Users : IdTable() { val name = varchar("name", length

    = 50).index() val age = integer("age") } class User(id: EntityID) : Entity(id) { var name: String by Users.name var age: Int by Users.age } retrieves the value and updates it automatically Delegated properties in frameworks