【发布时间】:2017-10-30 12:55:21
【问题描述】:
我有一个类,其构造函数采用 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。如果其中一个为空,则返回另一个,否则返回总和。
【问题讨论】:
-
请注意,这与更简单的
fun add = first?:0 + second?:0几乎相同。唯一的区别是当两者都为null时它不会返回null。 -
@MichaelAnderson 相同的编译错误
fun add(first : Int?, second : Int?) : Int? = first?:0 + second?:0 -
抱歉 - 这只是一个括号问题
fun add():Int = (first:?0) + (second:?0)适合我。