Improve sample comments.

Improve sample for lastIndex property.
This commit is contained in:
Ilya Gorbunov
2017-02-28 22:15:41 +03:00
parent 578dd1dc42
commit 75ae42121b
3 changed files with 15 additions and 6 deletions
@@ -28,7 +28,9 @@ class Collections {
@Sample
fun lastIndexOfList() {
assertPrints(emptyList<Any>().lastIndex, "-1")
assertPrints(listOf("a", "x", "y").lastIndex, "2")
val list = listOf("a", "x", "y")
assertPrints(list.lastIndex, "2")
assertPrints(list[list.lastIndex], "y")
}
}
@@ -84,11 +84,16 @@ class Maps {
@Sample
fun getOrPut() {
val map = mutableMapOf<String, Int?>()
assertPrints(map.getOrPut("x") { 2 }, "2")
assertPrints(map.getOrPut("x") { 3 }, "2") // still
assertPrints(map.getOrPut("x") { 2 }, "2")
// subsequent calls to getOrPut do not evaluate the default value
// since the first getOrPut has already stored value 2 in the map
assertPrints(map.getOrPut("x") { 3 }, "2")
// however null value mapped to a key is treated the same as the missing value
assertPrints(map.getOrPut("y") { null }, "null")
assertPrints(map.getOrPut("y") { 42 }, "42") // but!
// so in that case the default value is evaluated
assertPrints(map.getOrPut("y") { 42 }, "42")
}
@Sample
@@ -12,12 +12,14 @@ class Regexps {
val match = Regex("(\\w+) (\\d+)").find(inputString)!!
val (name, phone) = match.destructured
assertPrints(name, "John")
assertPrints(phone, "9731879")
assertPrints(name, "John") // value of the first group matched by \w+
assertPrints(phone, "9731879") // value of the second group matched by \d+
// group with the zero index is the whole substring matched by the regular expression
assertPrints(match.groupValues, "[John 9731879, John, 9731879]")
val numberedGroupValues = match.destructured.toList()
// destructured group values only contain values of the groups, excluding the zeroth group.
assertPrints(numberedGroupValues, "[John, 9731879]")
}
}