About Monkey 2 › Forums › Monkey 2 Programming Help › Generic array field syntax?
This topic contains 4 replies, has 3 voices, and was last updated by abakobo 4 weeks ago.
-
AuthorPosts
-
January 20, 2019 at 3:00 pm #15973
jondecker76
ParticipantI’ve been trying to figure this out for a bit now. I would like to have a generic array as a field in a class method, but I just can’t seem to get the syntax right. Ive tried..
Monkey12345field arr<T>[]field arr<T>:T[]field arr:<T>[]field arr<T>:[]and various other attempts, but just can’t seem to get it to work. I would like the “arr” field to be an array of whichever object I want to set it as. Is this possible?
Thanks
January 20, 2019 at 3:37 pm #15974
Danilo
ParticipantYou can use the type Variant to set it to whichever object you want.
Monkey123456789101112131415161718192021222324252627282930313233343536373839#Import "<monkey>"Using monkey..Class NameField arr:Variant[]Field anything:VariantEndFunction Main()Local c := New Namec.arr = New Variant[10]c.anything = 11Print Int( c.anything )c.anything = "String"Print String( c.anything )c.anything = New UByte[10]c.arr[0] = New Int[10]c.arr[1] = New Float[4]c.arr[2] = New String[5]c.arr[0].SetArrayElement( 5, 15)Local len := c.arr[0].GetArrayLength()For Local i := 0 Until lenPrint Int( c.arr[0].GetArrayElement( i ) )NextEndJanuary 20, 2019 at 3:50 pm #15975
Danilo
ParticipantA generic class with an array would look like this:
Monkey123456789101112131415161718192021#Import "<monkey>"Using monkey..Class Name<T>Field arr:T[]EndFunction Main()Local i := New Name<Int>i.arr = New Int[10]Local f := New Name<Float>f.arr = New Float[10]Local b := New Name<Byte>b.arr = New Byte[10]EndJanuary 20, 2019 at 7:17 pm #15976
jondecker76
ParticipantThanks! Quite helpful!
January 21, 2019 at 8:30 am #15979
abakobo
ParticipantGenerics are always associated with a function, class or struct. Generic interfaces were not available, I think it’s not available yet.
-
AuthorPosts
You must be logged in to reply to this topic.