https://kotlinlang.org logo
#announcements
Title
# announcements
l

LeoColman

07/19/2019, 2:03 PM
Guys, is it possible to create a function for both array and collection? They don't even have iterable in common 😞
g

gildor

07/19/2019, 2:05 PM
No, it's not possible
s

Suraj Shah

07/19/2019, 2:05 PM
you can make then depend on the output
Copy code
fun <T> someFunc() : T {}
g

gildor

07/19/2019, 2:05 PM
You can get iterator from array tho
s

Suraj Shah

07/19/2019, 2:05 PM
oh but they dont have anything in common.
l

LeoColman

07/19/2019, 2:06 PM
I can also go
toList()
, but I didn't want to create 2 functions xD
s

Suraj Shah

07/19/2019, 2:08 PM
not sure, but maybe you can try something like this:
Copy code
inline fun <reified T> someFunc()  : YourReturnType {
 // do your checks on T, if array or list 
}
l

LeoColman

07/19/2019, 2:11 PM
I don't think this will work in my case, as I need it to be an extension function, and I don't want it to be in the Any namespace
g

gildor

07/19/2019, 2:11 PM
This is a really bad way to implement it, what should happen if T is not List and not Array? IlligalArgumentException? It's essentially dynamic typing
Don't create 2 functions, just provide 1 function for List if it's not super performance critical (and I mean really critical)
l

LeoColman

07/19/2019, 2:12 PM
I'll create an overload for array that calls the toList
It's for a lib, we want to take the hassle of calling toList away from the user
g

gildor

07/19/2019, 2:13 PM
Why not just let user of your function to use toList, or even asLiwt to avoid data copying
l

LeoColman

07/19/2019, 2:16 PM
We wanted to make using these functions as easy as possible, with matchers for many types out-of-the-box
s

Suraj Shah

07/19/2019, 2:16 PM
yes. that would not work if it's not a list or an array.
d

diesieben07

07/19/2019, 2:16 PM
Most people won't be using an array.
l

LeoColman

07/19/2019, 2:17 PM
That's true
g

gildor

07/19/2019, 2:23 PM
Anyway, it depends on case, I would just provide extension for Iterable
l

LeoColman

07/19/2019, 2:23 PM
But Array isn't Iterable
Why isn't it, tho?
d

diesieben07

07/19/2019, 2:24 PM
Because Array is a low-level platform-specific primitive
g

gildor

07/19/2019, 2:41 PM
Array is not Iterable, but user of your API easily can convert it to any Iterable depending on case. Providing an array overload imo make sense only if this API is somehow optimized for array
A lot of stdlib extensions are just not available for array because of the same reason