The above example highlights JS's capability of storing any value type in an object. In the above demoObject we store an Integer, String, and a function.
Kotlin has this same functionality. However, unlike JS, Kotlin is a typed language. For the more straightforward types like Integer and String, Kotlin can infer the types automatically. However it needs a helping hand to determine what "type" a function is. The above example in Kotlin would be:
val demoObject = MutableMap<Int, Any> = mutableMapOf(
1 to 100,
2 to 'yolo',
3 to fun(x: Int):Int { return x*x }
)
println( (demoObject[3] as (Int)->Int)(2) ) //Outputs 4
In the last line above, note the use of the function type(Int) -> Int. Breaking down the line:
demoObject[3] will return a function, however Kotlin sees it as type "any" and cannot infer that it is a function
demoObject[3] as (Int)->Int casts the "Any" type to a function type, with the correct parameter and return type
(demoObject[3] as (Int)->Int)(2) wraps the function in brackets and passes a parameter of '2'
If you come from a JavaScript background, this syntax is probably familiar to you:
The above example highlights JS's capability of storing any value type in an object. In the above
demoObject
we store an Integer, String, and a function.Kotlin has this same functionality. However, unlike JS, Kotlin is a typed language. For the more straightforward types like Integer and String, Kotlin can infer the types automatically. However it needs a helping hand to determine what "type" a function is. The above example in Kotlin would be:
In the last line above, note the use of the function type (Int) -> Int. Breaking down the line:
demoObject[3]
will return a function, however Kotlin sees it as type "any" and cannot infer that it is a functiondemoObject[3] as (Int)->Int
casts the "Any" type to a function type, with the correct parameter and return type(demoObject[3] as (Int)->Int)(2)
wraps the function in brackets and passes a parameter of '2'Kotlin playground example