Kotlin 陣列 - last() 函式



Kotlin 陣列的 last() 函式檢索陣列中最後一個索引處的元素。如果陣列為空,則此函式會返回一個 NoSuchElementException 錯誤。

該函式的另一個過載版本接受一個謂詞,並返回陣列中對布林謂詞表達式返回 true 的最後一個元素。

語法

以下是 Kotlin 陣列 last() 函式的語法:

fun <T> Array<out T>.last(): T
or,
inline fun <T> Array<out T>.last(
   predicate: (T) -> Boolean
): T

引數

此函式不接受任何引數。

返回值

此函式返回任何資料型別的返回值,這取決於陣列最後一個元素的型別。

示例 1

以下是一個基本示例,建立一個大小為 5 的陣列,並使用 last() 函式獲取最後一個元素。

fun main(args: Array<String>) {
   var array = Array(5) { i -> i }
   try {
      val value = array.last()
      println("The value of the last element of the array is: $value")
   } catch (exception : Exception) {
      println("An element passing the given predicate does not exist or the array is empty")
	  println(exception.printStackTrace())
   }
}

輸出

以下是輸出:

The value of the last element of the array is: 4

示例 2

現在,讓我們看另一個示例,這裡我們建立一個儲存不同型別資料的陣列。然後,我們使用 last() 函式獲取最後一個索引的值:

fun main(args: Array<String>) {
   var array = arrayOf(10, 23.4, 'c', "tutorialspoint.com")
   try {
      // use the last() function
      val value = array.last()
      println("The value of the last element of the array is: $value")
   } catch (exception : Exception) {
      println("An element passing the given predicate does not exist or the array is empty")
      println(exception.printStackTrace())
   }
}

輸出

以下是輸出:

The value of the last element of the array is: tutorialspoint.com

示例 3

以下示例建立一個空陣列,並使用 last() 函式顯示最後一個索引的值:

fun main(args: Array<String>) {
   var array = emptyArray<String>()
   try {
      val value = array.last()
      println("The value of the last element of the array is: $value")
   } catch (exception : Exception) {
      println("An element passing the given predicate does not exist or the array is empty")
      println(exception.printStackTrace())
   }
}

輸出

以上程式碼生成以下輸出。如果發生異常:

An element passing the given predicate does not exist or the array is empty
kotlin_arrays.htm
廣告

© . All rights reserved.