## 2019年4月5日金曜日

### Kotlin - classes and objects - A Bit of Class - customer getter

Head First Kotlin: A Brain-Friendly Guide (Dawn Griffiths(著)、David Griffiths(著)、O'Reilly Media)のChapter 4(classes and objects - A Bit of Class)、Pool Puzzle(117)の解答を求めてみる。

コード

```class Rectangle(var width: Int, var height: Int) {
val isSquare: Boolean
get() = width == height
val area: Int
get() = width * height
}

fun main() {
val r = arrayOf(
Rectangle(1, 1),
Rectangle(1, 1),
Rectangle(1, 1),
Rectangle(1, 1)
)
for (x in 0..3) {
r[x].width = (x + 1) * 3
r[x].height = x + 5
print("Rectangle \$x has area \${r[x].area}. ")
println("It is \${if (r[x].isSquare) "" else "not "}a square.")
}
println()
// 他のループでの方法
for (x in 0 until r.size) {
r[x].width = (x + 1) * 3
r[x].height = x + 5
print("Rectangle \$x has area \${r[x].area}. ")
println("It is \${if (r[x].isSquare) "" else "not "}a square.")
}
println()
for ((x, rect) in r.withIndex()) {
rect.width = (x + 1) * 3
rect.height = x + 5
print("Rectangle \$x has area \${rect.area}. ")
println("It is \${if (rect.isSquare) "" else "not "}a ssquare.")
}
}```

```Rectangle 0 has area 15. It is not a square.
Rectangle 1 has area 36. It is a square.
Rectangle 2 has area 63. It is not a square.
Rectangle 3 has area 96. It is not a square.

Rectangle 0 has area 15. It is not a square.
Rectangle 1 has area 36. It is a square.
Rectangle 2 has area 63. It is not a square.
Rectangle 3 has area 96. It is not a square.

Rectangle 0 has area 15. It is not a ssquare.
Rectangle 1 has area 36. It is a ssquare.
Rectangle 2 has area 63. It is not a ssquare.
Rectangle 3 has area 96. It is not a ssquare.

Process finished with exit code 0
```