问题
I have a class whose constructor takes 2 int parameters (null values are allowed). Following is the compilation error.
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
Here is the NumberAdder class.
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
}
}
How can I resolve this issue? I want to return null if both are null. If one of them is null, return the other, and otherwise return the sum.
回答1:
Because first
and second
are vars, they will not be smart cast to non-null types when you do the if-test. Theoretically, the values can be changed by another thread after the if-test and before the +
. To solve this, you can assign them to local vals before you do the if-tests.
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
}
回答2:
The easiest fix for your code is to use val
instead of var
:
class NumberAdder (num1 : Int?, num2 : Int?) {
val first : Int?
val second : Int?
init{
first = num1
second = num2
}
...
I used here that Kotlin allows a val
to be assigned in the constructor.
回答3:
I experienced a similar issue with assertEquals.
My code was
assertEquals(
expeted = 42, // notice the missing c
actual = foo()
)
After I've fixed the typo, my IDE said I can't use named arguments with non-Kotlin functions, so I extracted the values to variables and everything started working as it should.
val expected = 42
val actual = foo()
assertEquals(expected, actual)
回答4:
This seems to work also.
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
}
}
来源:https://stackoverflow.com/questions/44255630/kotlin-compilation-error-none-of-the-following-functions-can-be-called-with-th