Is it possible to create array of function or lambda in kotlin? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Is it possible to create array of function or lambda in kotlin?

28th Nov 2019, 10:24 PM
Smit Kalkani
Smit Kalkani - avatar
7 Answers
+ 5
Reposted my DM here... You may store lambdas or functions into an array or list. They should all have the same prototype. Meaning parameters and return types defines a unique type. (Int, Int) -> Boolean is different from (Int) -> Unit. Technically, you can mix them as it creates Array<Any>, but you need to know all possible combinations so you can test which form was used.
29th Nov 2019, 2:10 AM
John Wells
John Wells - avatar
+ 3
That works. You will get an exception on line 10, if you change line 7 to a[1].
29th Nov 2019, 7:41 PM
John Wells
John Wells - avatar
+ 3
Yes. The is should tell you type, but fails on lambda. if (v is (Int)->Int) should be valid, but complains type erased, yet exception knows. Not sure what is going on. Will play later and let you know if I find a working method.
29th Nov 2019, 7:53 PM
John Wells
John Wells - avatar
29th Nov 2019, 7:27 PM
Smit Kalkani
Smit Kalkani - avatar
+ 2
Like this ???😅
29th Nov 2019, 7:28 PM
Smit Kalkani
Smit Kalkani - avatar
+ 2
Is this because of different prototype?
29th Nov 2019, 7:43 PM
Smit Kalkani
Smit Kalkani - avatar
+ 2
First I have tried with same prototype lambda but then I later I tried with different prototype of lambda
29th Nov 2019, 7:44 PM
Smit Kalkani
Smit Kalkani - avatar