From c6012f1facf0a07151f395351a9c310703fd2db9 Mon Sep 17 00:00:00 2001 From: James Strachan Date: Fri, 15 Jun 2012 12:02:17 +0100 Subject: [PATCH] applied pull request with thanks https://github.com/JetBrains/kotlin/pull/46 --- libraries/stdlib/src/kotlin/JUtil.kt | 8 ++++++++ libraries/stdlib/test/ListTest.kt | 9 +++++++++ 2 files changed, 17 insertions(+) diff --git a/libraries/stdlib/src/kotlin/JUtil.kt b/libraries/stdlib/src/kotlin/JUtil.kt index 200fcd37353..60137a14966 100644 --- a/libraries/stdlib/src/kotlin/JUtil.kt +++ b/libraries/stdlib/src/kotlin/JUtil.kt @@ -172,6 +172,14 @@ val List.last : T? return if (s > 0) this.get(s - 1) else null } +/** + * Returns the index of the last item in the list or -1 if the list is empty + * + * @includeFunctionBody ../../test/ListTest.kt lastIndex + */ +val List.lastIndex : Int + get() = this.size - 1 + /** * Returns the first item in the list * diff --git a/libraries/stdlib/test/ListTest.kt b/libraries/stdlib/test/ListTest.kt index 97136d5a993..bd7268ef142 100644 --- a/libraries/stdlib/test/ListTest.kt +++ b/libraries/stdlib/test/ListTest.kt @@ -1,5 +1,6 @@ package test.collections +import java.util.ArrayList import kotlin.test.* import org.junit.Test as test @@ -36,4 +37,12 @@ class ListTest { } assertEquals(data.size(), index) } + + test fun lastIndex() { + val emptyData = ArrayList() + val data = arrayList("foo", "bar") + + assertEquals(-1, emptyData.lastIndex) + assertEquals(1, data.lastIndex) + } }