MST

星途 面试题库

面试题:Kotlin运算符重载与泛型结合及约定机制的深度应用

设计一个泛型类`Matrix<T>`用于表示矩阵,其中`T`可以是`Int`、`Double`等数值类型。要求重载常见的矩阵运算运算符(如加法`+`、乘法`*`),并利用Kotlin的约定机制实现矩阵的索引访问(类似二维数组`matrix[i][j]`),同时要考虑泛型类型的兼容性和运算规则的合理性,写出完整的Kotlin代码实现。
28.9万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
class Matrix<T : Number> private constructor(private val rows: Int, private val cols: Int, private val data: Array<Array<T>>) {
    constructor(rows: Int, cols: Int) : this(rows, cols, Array(rows) { Array(cols) { 0 as T } })

    operator fun get(row: Int, col: Int): T = data[row][col]

    operator fun set(row: Int, col: Int, value: T) {
        data[row][col] = value
    }

    operator fun plus(other: Matrix<T>): Matrix<T> {
        require(rows == other.rows && cols == other.cols) { "Matrices must have the same dimensions for addition" }
        val result = Matrix<T>(rows, cols)
        for (i in 0 until rows) {
            for (j in 0 until cols) {
                result[i, j] = when (data[i][j]) {
                    is Int -> (data[i][j] as Int) + (other[i, j] as Int) as T
                    is Double -> (data[i][j] as Double) + (other[i, j] as Double) as T
                    else -> throw UnsupportedOperationException("Unsupported type for addition")
                }
            }
        }
        return result
    }

    operator fun times(other: Matrix<T>): Matrix<T> {
        require(cols == other.rows) { "Number of columns in the first matrix must be equal to the number of rows in the second matrix for multiplication" }
        val result = Matrix<T>(rows, other.cols)
        for (i in 0 until rows) {
            for (j in 0 until other.cols) {
                var sum = 0.0
                for (k in 0 until cols) {
                    sum += when (data[i][k]) {
                        is Int -> (data[i][k] as Int) * (other[k, j] as Int)
                        is Double -> (data[i][k] as Double) * (other[k, j] as Double)
                        else -> throw UnsupportedOperationException("Unsupported type for multiplication")
                    }
                }
                result[i, j] = sum as T
            }
        }
        return result
    }
}