我有一个类,它的构造函数接受2个int参数(允许空值)。以下是编译错误。
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
下面是NumberAdder类。
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。如果其中一个为空,则返回另一个,否则返回总和。
发布于 2017-05-30 15:14:51
因为first
和second
是var,所以在执行if测试时不会将它们智能转换为非空类型。从理论上讲,这些值可以由另一个线程在if-test之后和+
之前更改。要解决这个问题,您可以在执行if-test之前将它们分配给本地函数。
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
}
发布于 2017-05-30 18:47:34
对代码最简单的修复方法是使用val
而不是var
class NumberAdder (num1 : Int?, num2 : Int?) {
val first : Int?
val second : Int?
init{
first = num1
second = num2
}
...
我在这里使用的Kotlin允许在构造函数中分配一个val
。
发布于 2018-08-07 01:14:22
我在使用assertEquals时遇到了类似的问题。
我的代码是
assertEquals(
expeted = 42, // notice the missing c
actual = foo()
)
在我修复了拼写错误后,我的IDE告诉我不能将命名参数用于非Kotlin函数,所以我将值提取到变量中,一切都开始正常工作。
val expected = 42
val actual = foo()
assertEquals(expected, actual)
https://stackoverflow.com/questions/44255630
复制相似问题