Kotlin 陣列 - component5() 函式



Kotlin 陣列的 component5() 函式檢索陣列物件的第 5 個元素,或第 4 個索引的值。如果陣列大小小於 5 或為空,則此函式會丟擲 IndexOutOfBoundsException 異常。

語法

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

operator fun <T> List<T>.component5(): T

引數

此函式不接受任何引數。

返回值

此函式返回任何資料型別的陣列元素。

示例 1

在本例中,讓我們看看如何使用 component5() 函式確定陣列中第 4 個索引(即第 5 個元素)的值。

fun main(args: Array<String>) {
   var array = Array(10) { i -> i }
   try {
      val value = array.component5()
      println("The 5th element of the array is: $value")
   } catch (exception : Exception) {
      println("Array length is smaller than four")
      println(exception.printStackTrace())
   }
}

輸出

以下是輸出:

The 5th element of the array is: 4

示例 2

現在,讓我們看另一個例子,在這裡我們建立一個儲存不同型別資料的陣列。然後,我們使用 component5() 函式獲取第 5 個元素:

fun main(args: Array<String>) {
   var array = arrayOf(10, 23.4, 'c', "tutorialspoint.com", "tutorix")
   try {
      // use the component5() function
      val value = array.component5()
      println("The value of the 4th index of the array is: $value")
   } catch (exception : Exception) {
      println("Array length is smaller than four")
      println(exception.printStackTrace())
   }
}

輸出

以下是輸出:

The value of the 4th index of the array is: tutorix

示例 3

此示例建立一個大小為 4 的陣列,並使用 component5() 函式顯示陣列中第 5 個元素(即第 4 個索引)的值:

fun main(args: Array<String>) {
   var array = Array(4){ i -> i }
   try {
      val value = array.component5()
      println("The value of the 5th element of an array is: $value")
   } catch (exception : Exception) {
      println("Array length is smaller than 5")
      println(exception.printStackTrace())
   }
}

輸出

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

Array length is smaller than 5
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
kotlin_arrays.htm
廣告

© . All rights reserved.