Kotlin 陣列 - component2() 函式



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

語法

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

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

引數

此函式不接受任何引數。

返回值

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

示例 1

在下面的示例中,讓我們看看如何使用 component2() 函式確定陣列中第一個索引(即第二個元素)的值。

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

輸出

以下是輸出:

The value of the second element of the array is: 1

示例 2

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

fun main(args: Array<String>) {
   var array = arrayOf(10, 23.4, 'c', "tutorialspoint.com")
   try {
      // use the component2() function
      val value = array.component2()
      println("The value of the second 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 second element of the array is: 23.4

示例 3

下面的示例建立一個空陣列,並使用 component2() 函式顯示陣列中第一個索引(即第二個元素)的值:

fun main(args: Array<String>) {
   var array = emptyArray<String>()
   try {
      val value = array.component2()
      println("The value of the second 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
廣告