Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Compilation Error : None of the following functions can be called with the arguments supplied

Tags:

int

kotlin

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.

like image 534
a.r. Avatar asked May 30 '17 07:05

a.r.


3 Answers

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
}
like image 98
marstran Avatar answered Oct 19 '22 20:10

marstran


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.

like image 4
voddan Avatar answered Oct 19 '22 20:10

voddan


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)
like image 1
Vladimir Kondenko Avatar answered Oct 19 '22 21:10

Vladimir Kondenko