You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
, p [][ text "Traits can combine required properties with methods that perform meaningful operations using those properties:"]
175
+
, viewCodeBlock """trait Describable = (name: String, age: Int) do
176
+
describe :: Self -> String
177
+
isAdult :: Self -> Bool
178
+
end
179
+
180
+
struct Person = (name: String, age: Int)
181
+
182
+
impl Describable for Person = do
183
+
describe self = self.name ++ " is " ++ (self.age as String) ++ " years old"
184
+
isAdult self = self.age >= 18
185
+
end
186
+
187
+
let main: IO = do
188
+
let p = Person { name: "Alice", age: 30 }
189
+
println (describe p)
190
+
println (isAdult p)
191
+
end""" onLoadCode True"indigo"
192
+
, p [][ text "In this example, the Describable trait requires name and age properties, and provides methods that use these properties to compute results. The describe method formats a string using both properties, while isAdult performs a validation check."]
193
+
, p [][ text "You can also use the is clause with traits that have both required properties and methods:"]
194
+
, viewCodeBlock """trait Describable = (name: String, age: Int) do
195
+
describe :: Self -> String
196
+
isAdult :: Self -> Bool
197
+
end
198
+
199
+
struct Person = (name: String, age: Int) is Describable
200
+
201
+
impl Describable for Person = do
202
+
describe self = self.name ++ " is " ++ (self.age as String) ++ " years old"
203
+
isAdult self = self.age >= 18
204
+
end
205
+
206
+
let main: IO = do
207
+
let p = Person { name: "Bob", age: 17 }
208
+
println (describe p)
209
+
println (isAdult p)
210
+
end""" onLoadCode True"indigo"
211
+
, p [][ text "The compiler validates that structs implementing the trait have all required properties, and you must provide implementations for all trait methods."]
212
+
, p [][ text "Trait dispatch in Indigo requires concrete types at compile time. When you call a trait method, the compiler must be able to determine the concrete struct type to select the correct implementation. This means trait methods work best when called directly on concrete struct instances, rather than through polymorphic functions that accept Any."]
173
213
, h3 [][ text "Trait Refinements"]
174
214
, p [][ text "Traits can also have refinement types, similar to structs. These refinements are checked when creating struct literals that implement the trait:"]
0 commit comments