Hi, does someone knows how to defined a function o...
# getting-started
x
Hi, does someone knows how to defined a function of any type in kotlin ? no matter what the param and return are . In typescript, we can do it like this:
Copy code
type Fn = (...args:any[]) -> any
but I don't know how to do it in Kotlin.
j
In Kotlin,
Any?
is the supertype of all types, so you could use that for arguments and the return value. If you also want a variable number of arguments, you can use `vararg`:
Copy code
fun takeAnything(vararg args: Any?): Any?
x
but how to defined a type like this ? say I wanna define a map with key of type string, and the value is a funciton. ie :
Copy code
val something  = mapOf<String,???>("+" to ::plus, "-" to :: sub)
what should I put here instead of ??? it is a function
h
mapOf<String, Function<*>>
r
Can't try it right now, but maybe
Function<*>
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-function.html
@hfhbd Beat me to it 😀
x
oops, seems not work,
image.png
j
You're putting the
<...>
in the wrong place, they should be between
mapOf
and the opening parenthesis
x
yes you are right
my bad
I just find it
😅
h
But if you only need to store operators, you could find the common function signature and use it as parameter, for example mapOF<String, (Int, Int) -> Int> for integers of course
x
Yes, it is a demo here, I'm learning kotlin maybe someday will encounter more complicate situation, thanks. but one more question, how to learn Kotlin types? I mean in TS there is project named TypeChallenge on github (https://github.com/type-challenges/type-challenges). we can do some exercise to learn about types in TS.