多类型ArrayList作为Kotlin中的函数参数

我想向函数发送包含多个类型的数组列表(我知道这不是一个好习惯,这是有目的的)。

我不知道该函数的“数字”参数应使用哪种类型。然后如何遍历它。我尝试过List,但是需要一个。

谢谢。

fun sum(numbers : ArrayList) : Double
{
    var sum:Double = 0.0

    for(i in 0 until numbers.itemCount)
    {
        var temp:Double = numbers.getItem(i).toDouble()
        sum = sum + temp
    }

    return sum
}

fun main()
{
    var ar = listOf("99", 1, 3.1)

    println(sum(ar))
}
评论
  • alber1986
    alber1986 回复

    You can't do this without checking specific types. String.toDouble() is not the same function as Number.toDouble() even though they look the same. Your ArrayList type has to be Any to be able to accept both Strings and Numbers. Then you have to explicitly check the type. You will have to handle the case where something is not a String or a Number by throwing an exception.

    You might as well make the type List<Any> instead of ArrayList<Any> to avoid the unnecessary restriction on input.

    fun sum(numbers : List<Any>) : Double
    {
        var sum: Double = 0.0
    
        for(item in numbers) {
            val temp = when (item) {
                is String -> item.toDouble()
                is Number -> item.toDouble()
                else -> error("Unsupported type")
            }
            sum += temp
        }
    
        return sum
    }
    

    There is an existing sum() function for lists of numbers, so you can simplify this code by converting the list into a List<Double> using the map() function:

    fun sum(numbers : List<Any>) : Double = numbers.map {
        when (it) {
            is String -> it.toDouble()
            is Number -> it.toDouble()
            else -> error("Unsupported type")
        }
    }.sum()