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.
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
}
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With