COMMUNITY

Can one use two generic types in a function?

generic

(Kyliathy) #1

This works fine:
private function loadFile<T> (url: String, type: Class<T>, container: Array<T>) call: loadFile(fileURL, MyClass, Array<MyClass>);

But not this one:
private function loadFile<T, M> (url: String, type: Class<T>, container: Array<T>, container2: Array<M>) call loadFile(fileURL, MyClass, Array<MyClass>, Array<String>);

Error:
Error: String should be loadFile.M
Error: For function argument ‘x’


(Valentin Lemière) #2

Is the error on calling the function or inside it?
There should be no problem with the call considering the function signature.


(Juraj Kirchheim) #3

Seems to be working just fine: https://try.haxe.org/#fa8d7


(Kyliathy) #4

Very interesting. Thank you back2dos for demonstrating! Using your sample, I have found something interesting. Check what I did to your sample. I just added a simple call to the actual object and… boom :).

https://try.haxe.org/#F7048

It DOES work if, in the modified sample, you change the signature to:

static function loadFile<T, M> (url: String, type: Class<T>, container: Array<T>, container2: Array<String>)

But this kind of defeats the purpose, since I want to have generic types.

So basically the error is when I call the function that uses that type. It complains that I should be using M instead of String.

I tried casting, but casting doesn’t work for type parameters.


(Kyliathy) #5

It’s inside the function. I updated back2dos’s sample here:

https://try.haxe.org/#F7048


(Rudy Ges) #6

Well yes, inside the function it is not an array of String but an array of M. container2.push("test") also defeats the purpose of having generic types.


(Kyliathy) #7

Yeah, you’re right :). I understand now how and why it works. It works only if using the actual types directly in the calls where they are required. Array.push won’t work unless the type is the same generic type.

For example I can’t call this if url is a generic type:

var fileRequest: Http = new Http(url);

Unless I use:

var fileRequest: Http = new Http(cast(url, String));

However, I guess this second case would work if I know that the type converts to String?


(Kyliathy) #8

@kLabz I edited my response above. I’m curious if it is considered an acceptable use of generic types to create such a function for use for those generic types that can convert to string :).