Thursday, August 1, 2019

Kotlin in Action: Answers to Chapter 7 Exercises

Here's the answer to the chapter 7 exercise.

Exercise: Operator Overloads for Json Manipulation

Immutable

operator fun JsonObject.plus(other: JsonObject): JsonObject =
  copy().apply {
    other.forEach { (key, value) -> put(key, value) }
  }

operator fun JsonObject.plus(pair: Pair<String, *>): JsonObject =
  copy().put(pair.first, pair.second)

operator fun JsonObject.minus(key: String): JsonObject =
  copy().apply { remove(key) }

operator fun JsonObject.minus(keys: Collection<String>): JsonObject =
  copy().apply {
    keys.forEach { remove(it) }
  }

operator fun JsonArray.plus(other: JsonArray): JsonArray =
  copy().addAll(other)

operator fun JsonArray.plus(item: Any?): JsonArray =
  copy().add(item)

operator fun JsonArray.minus(other: JsonArray): JsonArray =
  copy().apply {
    other.forEach { remove(it) }
  }

operator fun JsonArray.minus(item: Any?): JsonArray =
  copy().apply { remove(item) }

operator fun JsonArray.minus(index: Int): JsonArray =
  copy().apply { remove(index) }

Mutable

operator fun JsonObject.plusAssign(other: JsonObject) =
  other.forEach { (key, value) -> put(key, value) }

operator fun JsonObject.plusAssign(pair: Pair<String, *>) {
  put(pair.first, pair.second)
}

operator fun JsonObject.minusAssign(key: String) {
  remove(key)
}

operator fun JsonObject.minusAssign(keys: Collection<String>) =
  keys.forEach { remove(it) }

operator fun JsonArray.plusAssign(other: JsonArray) {
  addAll(other)
}

operator fun JsonArray.plusAssign(item: Any?) {
  add(item)
}

operator fun JsonArray.minusAssign(other: JsonArray) {
  other.forEach { remove(it) }
}

operator fun JsonArray.minusAssign(item: Any?) {
  remove(item)
}

operator fun JsonArray.minusAssign(index: Int) {
  remove(index)
}