HelloCW
HelloCW

Reputation: 2335

I get "Type mismatch" error when I use a function as parameter in Kotlin?

I hope use the function AA as the parameter of the function BB in the following code, but I get the two errors.

Error 1: I hope to assign the result of function cc to dd, but I failed.

Error 2: I hope to invoke the function BB, but the parameter AA(3) is incorrect.

How can I fix the errors? Thanks!

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        BB(1,AA(3)); //Error 2
    }



    fun AA(aa:Int): Int{
       return aa+10
    }

    fun BB(bb:Int, cc:(Int) -> Int){
        val dd:Int=cc(Int); //Error 1
        Toast.makeText(getApplicationContext(), bb+dd, Toast.LENGTH_LONG).show();
    }

}

Upvotes: 0

Views: 436

Answers (2)

Martin Marconcini
Martin Marconcini

Reputation: 27246

Your Kotlin syntax is wrong.

How you have it written, the BB method would be:

fun BB(bb: Int, cc: Int) {

What you’re passing BB is the RESULT of the AA function (aka: an Int).

In other words, why are you receiving a function (AA) inside (BB) if you are already invoking the function when you’re calling “BB”. Since AA takes an Int and returns an Int, the signature for the BB function expects just two ints. The Call to AA(Int) happened on your ERROR 2 line.

It’s not clear what you’re trying to do (given the code of your Toast), but you can use TypeAlias & Bound references like this:

typealias SomeType = (Int) -> Int

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val a = this::AA // Save a Bound Reference to the function.

        BB(1, a) // Call BB and pass a value and a function
    }

    fun AA(aa: Int): Int {
        return aa + 10
    }

    fun BB(bb: Int, cc: SomeType) {
        val dd = cc(bb) // call `cc` which is really `AA(Int) -> Int`
        Toast.makeText(getApplicationContext(), dd, Toast.LENGTH_LONG).show()
    }
}

Upvotes: 2

배준모
배준모

Reputation: 601

try this.

fun AA(aa: Int): Int {
        return aa + 10
    }

    fun BB(bb: Int, cc: Int) {
        val dd: Int = cc
        Toast.makeText(getApplicationContext(), bb + dd, Toast.LENGTH_LONG).show()
    }

Upvotes: 0

Related Questions