Zorgan
Zorgan

Reputation: 9123

Type inference in kotlin lambda function not working

My lambda:

val streetNumber: Int = {
        num: Int -> num / 4
}

How come I am getting this error:

error: type mismatch: inferred type is (Int) -> Int but Int was expected
val streetNumber: Int = {
                        ^

My knowledge of my code block is:

  1. The first Int means I am returning an Int type.
  2. The 2nd Int means I've declared the type of num to be Int.

Are any of those statements wrong?

Upvotes: 0

Views: 844

Answers (3)

Jay Mungara
Jay Mungara

Reputation: 7150

you can do it easily like,

val streetNumber= {
    num: Int -> num / 4
}

then, call it like,

val number=40
println(div(number))

this is the simplest way, to do this thing.

Upvotes: 0

forpas
forpas

Reputation: 164069

Declaring:

val streetNumber: Int

means that streetNumber's data type is Int and not that the return type is Int.
So this conflicts with the assignment:

val streetNumber = { num: Int -> num / 4 }

In these cases trust the inferred data type which is (Int) -> Int

The variable streetNumber is not a variable referencing an integer value,
like for example: val x: Int = 0.
It is a variable referencing a Lambda expression which returns an integer value.
You can use it like this:

val streetNumber = { num: Int -> num / 4 }
val x: Int = streetNumber(12)
println(x)

which will print

3

Upvotes: 0

s1m0nw1
s1m0nw1

Reputation: 81879

Your variable type Int is not correct in this case, what you want to do instead:

val streetNumber: (Int) -> Int = {
    num: Int -> num / 4
}

Upvotes: 1

Related Questions