Objects
Draft uses records (also called structs) to define custom data structures.
Defining Records
Section titled “Defining Records”record User name: String age: Int email: Stringfin record.Creating Instances
Section titled “Creating Instances”@user = User { name: "Alice", age: 30, email: "alice@example.com"}Accessing Fields
Section titled “Accessing Fields”Use # for member access:
write(@user#name) @// "Alice"write(@user#age) @// 30Mutable Fields
Section titled “Mutable Fields”Records are immutable by default. Use mut for mutable instances:
mut @user = User { name: "Alice", age: 30, email: "alice@example.com"}
@user#age = 31 @// OK: user is mutableRecord Actions
Section titled “Record Actions”Define actions on records:
record User name: String age: Int email: Stringfin record.
impl User action greet(@self: User) -> String return "Hello, I'm " + @self#name fin action.
action is_adult(@self: User) -> Boolean return @self#age >= 18 fin action.
action birthday(@self: mut User) @self#age = @self#age + 1 fin action.fin impl.
@user = User { name: "Alice", age: 30, email: "alice@example.com" }write(@user#greet()) @// "Hello, I'm Alice"write(@user#is_adult()) @// trueConstructor Pattern
Section titled “Constructor Pattern”Create a constructor function:
record User name: String age: Int email: Stringfin record.
action new_user(@name: String, @age: Int, @email: String) -> User return User { name: @name, age: @age, email: @email }fin action.
@user = new_user("Alice", 30, "alice@example.com")Default Values
Section titled “Default Values”Provide default values for fields:
record Config host: String = "localhost" port: Int = 8080 debug: Boolean = falsefin record.
@config = Config {} @// Uses all defaults@custom = Config { host: "0.0.0.0", port: 3000 }Generic Records
Section titled “Generic Records”Records can be generic:
record Pair<A, B> first: A second: Bfin record.
@pair = Pair<Int, String> { first: 1, second: "one" }Record Inheritance
Section titled “Record Inheritance”Records can extend other records:
record Shape x: Float y: Floatfin record.
record Circle extends Shape radius: Floatfin record.
@circle = Circle { x: 0.0, y: 0.0, radius: 5.0 }Destructuring Records
Section titled “Destructuring Records”{@name, @age} = @user@// name = "Alice", age = 30Record Equality
Section titled “Record Equality”Records implement structural equality:
@a = User { name: "Alice", age: 30, email: "a@b.com" }@b = User { name: "Alice", age: 30, email: "a@b.com" }@a == @b @// trueRecord Cloning
Section titled “Record Cloning”@original = User { name: "Alice", age: 30, email: "a@b.com" }@copy = @original#clone()Singleton Objects
Section titled “Singleton Objects”For singleton patterns:
singleton Logger action log(@message: String) write("[LOG] " + @message) fin action.fin singleton.
@Logger#log("Hello")Type Aliases for Records
Section titled “Type Aliases for Records”type Point = { x: Float, y: Float }Next Steps
Section titled “Next Steps”Continue to Enums for enumerated types.
