Kotlin 陣列 - sumOf() 函式



Kotlin 陣列的 sumOf() 函式用於返回對陣列中每個元素應用選擇器函式後生成的陣列元素的總和。

此函式可以用於整數、浮點數和其他數值型別的陣列。它不適用於字串或字元資料型別。

在最新版本的 Kotlin 中,sumBy() 函式已被棄用。建議使用 sumOf() 函式替換 sumBy() 函式。

語法

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

fun <T> Array<out T>.sumOf(selector: (T) -> Int): Int

引數

此函式接受 selector 作為引數。

返回值

此函式返回由選擇器函式指定的所有值的總和。

示例 1

以下是一個演示 sumOf() 函式用法的基本示例:

fun main(args: Array<String>){
   var arr = arrayOf(3, 4, 5, 6)
   print("Array elements: ")
   println(arr.joinToString())

   // Sum of all element of an array
   val total = arr.sumOf({it})
   println("Sum of array's element: "+ total)
}

輸出

以上程式碼生成以下輸出:

Array elements: 3, 4, 5, 6
Sum of array's element: 18

示例 2

讓我們來看另一個示例。在這裡,我們使用 sumOf 函式計算元素及其雙倍值的總和:

fun main(args: Array<String>){
   var arr = arrayOf(1, 2, 3, 4, 5)
   println("Array elements: ")
   arr.forEach { println(it) }

   //Sum of all element with their double value
   println("Sum of array's element ${arr.sumOf{it*2}}")
}

輸出

以下是輸出:

Array elements: 
1
2
3
4
5
Sum of array's element 30

示例 3

讓我們看下面的例子,我們有一個 Product 物件陣列,我們想使用 sumOf() 函式計算所有產品的總價格:

data class Product(val name: String, val price: Double, val quantity: Int)

fun main(args: Array<String>) {
   val products = arrayOf(
      Product("Laptop", 999.99, 1),
      Product("Mouse", 19.99, 2),
      Product("Keyboard", 49.99, 1),
      Product("Monitor", 199.99, 2)
   )
   // Calculate the total price of all products
   val totalPrice = products.sumOf { it.price * it.quantity }

   // Display the result
   println("The total price of all products is: $$totalPrice")
}

輸出

以上程式碼產生以下輸出:

The total price of all products is: $1489.94
kotlin_arrays.htm
廣告
© . All rights reserved.