Kotlin编译错误:使用提供的参数无法调用以下任何函数 [英] Kotlin Compilation Error : None of the following functions can be called with the arguments supplied

查看:828
本文介绍了Kotlin编译错误:使用提供的参数无法调用以下任何函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个其构造函数带有2个int参数的类(允许使用空值). 以下是编译错误.

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

这是NumberAdder类.

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.

推荐答案

由于firstsecond是var,因此在执行if-test时,它们不会被智能地转换为非null类型.从理论上讲,值可以在if-test之后和+之前由另一个线程更改.为了解决这个问题,您可以在执行if-tests之前将它们分配给本地val.

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
}

这篇关于Kotlin编译错误:使用提供的参数无法调用以下任何函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆