- Kotlin 教程
- Kotlin - 首頁
- Kotlin - 概述
- Kotlin - 環境設定
- Kotlin - 架構
- Kotlin - 基本語法
- Kotlin - 註釋
- Kotlin - 關鍵字
- Kotlin - 變數
- Kotlin - 資料型別
- Kotlin - 運算子
- Kotlin - 布林值
- Kotlin - 字串
- Kotlin - 陣列
- Kotlin - 範圍
- Kotlin - 函式
- Kotlin 控制流
- Kotlin - 控制流
- Kotlin - if...else 表示式
- Kotlin - when 表示式
- Kotlin - for 迴圈
- Kotlin - while 迴圈
- Kotlin - break 和 continue
- Kotlin 集合
- Kotlin - 集合
- Kotlin - 列表
- Kotlin - 集合
- Kotlin - 對映
- Kotlin 物件和類
- Kotlin - 類和物件
- Kotlin - 建構函式
- Kotlin - 繼承
- Kotlin - 抽象類
- Kotlin - 介面
- Kotlin - 可見性控制
- Kotlin - 擴充套件
- Kotlin - 資料類
- Kotlin - 密封類
- Kotlin - 泛型
- Kotlin - 委託
- Kotlin - 解構宣告
- Kotlin - 異常處理
- Kotlin 有用資源
- Kotlin - 快速指南
- Kotlin - 有用資源
- Kotlin - 討論
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
廣告