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 

我的数字加法器类如下所示:

 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 } } 

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

因为firstsecond是变量,所以当你执行if-test的时候,它们不会变成非空的类型。 理论上,这些值可以在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 } 

您的代码最简单的修复方法是使用val而不是var

 class NumberAdder (num1 : Int?, num2 : Int?) { val first : Int? val second : Int? init{ first = num1 second = num2 } ... 

我在这里使用Kotlin允许在构造函数中赋值val

这似乎也工作。

 fun main(args: Array<String>) { var numberAdder : NumberAdder = NumberAdder(10, 20) var result : Int? = numberAdder.add() println("$result") } class NumberAdder (num1 : Int?, num2 : Int?) { var first : Int? var second : Int? init{ first = num1 second = num2 } fun add() : Int?{ if(first != null && second != null){ return first as Int + second as Int } if(first == null){ return second } if(second == null){ return first } return null } }