Map with function

I tried a list with function (ki-shell 1.7.0) :

[48] val square = fun(x:Int) : Int {return x*x}
[49] val cube = fun(x:Int) : Int {return x*x*x}
[50] val l_power=mutableListOf(square, cube)
[51] l_power[0](5)
res27: Int = 25

Now with a map

[52] val m_power=mutableMapOf("power2" to square, "power3" to cube)
type results for list or map seems equal

[53] m_power["power2"]
res29: Function1<Int, Int> = (kotlin.Int) -> kotlin.Int
[54] l_power[0]
res30: Function1<Int, Int> = (kotlin.Int) -> kotlin.Int

Now if I call function there is an error :

[55] m_power["power2"](5)
ERROR Reference has a nullable type '((Int) -> Int)?', use explicit '?.invoke()' to make a function-like call instead (Line_56.kts:1:1)

Where is my mistake?

The get operator on map returns a nullable type, since it doesn’t know if the key exists in the map at all.

You can use getValue - Kotlin Programming Language instead which will return a non-nullable type, but throw if the value isn’t there.


thanks it works :


res34: Int = 25

But still, why does the shell print the wrong type for m_power[“power2”]? It should be a nullable type, but in the output in the OP it’s a non-nullable type.

The shell prints the type of the actual returned value (which is not null in your case), not the return type of the invoked function.


Why should it be nullable? It’s type of the value it got and it got value previously assigned to square

1 Like

Right, thanks — I missed that it was printing the result type, not the expression type.