https://kotlinlang.org logo
#flow
Title
# flow
a

asad.awadia

03/16/2023, 12:20 AM
How can i hold a function with signature
Flow<T> -> U
in a hashmap ? (As the value - key can be string/int)
b

bezrukov

03/16/2023, 10:16 AM
smth like this
Copy code
val map = HashMap<String, (Flow<Int>) -> Unit>()
and then
Copy code
map["test"] = { flow -> Unit }
a

asad.awadia

03/16/2023, 12:59 PM
Not int and unit though - it can be any type..
k

Kevin Worth

03/16/2023, 3:01 PM
Does this work?
Copy code
val map = HashMap<String, (Flow<Any>) -> Unit>()
a

asad.awadia

03/16/2023, 3:05 PM
Yes it does But i need the type around so that i can decode a json string to that type (T - which can be anything) and then invoke the handler with that type
k

Kevin Worth

03/16/2023, 4:03 PM
Have you looked into the
out
keyword? I’m not super strong with it, but perhaps it could help… https://kotlinlang.org/docs/generics.html#declaration-site-variance (may need to scroll up as the docs just above that have quite a bit of context/introduction)
a

asad.awadia

03/16/2023, 4:11 PM
Yes - not sure if it will help I will go through the doc again thanks
b

bezrukov

03/16/2023, 5:52 PM
can you elaborate your usecase? It's impossible to just declare
T
(it's not a flow problem, you can't also declare a
val property: T
). It's impossible to parametrize a property, usually you parametrize either class or function. If you did that - you will be able to just declare it with
T
(and
U
instead of Unit). Otherwise you have to write
val map = HashMap<String, (Flow<Any>) -> Any>()
as mentioned above and do an unchecked cast
a

asad.awadia

03/16/2023, 10:59 PM
Yes you are right. It is not really a flow problem I want to hold a list of handlers that can take in user defined input types (could be string or int or a class) Then at some later point i want to take input from somewhere else, convert it to the right type as expected by the handler and then invoke that handler So if 1 handler was string and 1 was double - and at some later point i get input 88 - i will invoke the first handler with "88" and the other with 88.0
@bezrukov any idea?
3 Views