Kotlin编译错误:使用提供的参数无法调用以下任何函数

a.r*_*.r. 11 int kotlin

我正在尝试学习Kotlin,并在kotlin中创建了一个简单的类,在其构造函数中使用两个int,然后添加它们.这些int可以为null.

I am receiving compilation error as:

None of the following functions can be called with the arguments supplied: 
public final operator fun plus(other: Byte): Int defined in kotlin.Int
public final operator fun plus(other: Double): Double defined in kotlin.Int
public final operator fun plus(other: Float): Float defined in kotlin.Int
public final operator fun plus(other: Int): Int defined in kotlin.Int
public final operator fun plus(other: Long): Long defined in kotlin.Int
public final operator fun plus(other: Short): Int defined in kotlin.Int
Run Code Online (Sandbox Code Playgroud)

我的号码加法器类如下:

class NumberAdder (num1 : Int?, num2 : Int?) {

    var first : Int? = null
    var second : Int? = null

    init{
    first = num1
    second = num2
    }

fun add() : Int?{

    if(first != null && second != null){
        return first + second
    }

    if(first == null){
        return second
    }

    if(second == null){
        return first
    }

    return null
}

}
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题.如果两者都为null,我想返回null.如果其中一个为null,则返回另一个否则返回总和.

mar*_*ran 7

因为first并且second是vars,所以当你进行if-test时,它们不会被智能地转换为非null类型.从理论上讲,在if-test之后和之前,可以通过另一个线程来更改这些值+.要解决此问题,可以在执行if-tests之前将它们分配给本地val.

fun add() : Int? {
    val f = first
    val s = second

    if (f != null && s != null) {
        return f + s
    }

    if (f == null) {
        return s
    }

    if (s == null) {
        return f
    }

    return null
}
Run Code Online (Sandbox Code Playgroud)