dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
12 stars 0 forks source link

Kotlin Maps and Function Types #57

Open dvas0004 opened 5 years ago

dvas0004 commented 5 years ago

If you come from a JavaScript background, this syntax is probably familiar to you:

const demoObject ={
   1: 100,
   2: 'yolo',
   3: (x) => x*x
}
console.log( demoObject[3](2) ) // outputs: 4

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:

Kotlin playground example

dvas0004 commented 5 years ago

https://blog.kotlin-academy.com/kotlin-programmer-dictionary-function-type-vs-function-literal-vs-lambda-expression-vs-anonymous-edc97e8873e