渲染zh-Hant

類型

Translation status: 繁體中文 reader-locale proof. Term names and code fences follow the zh-Hant pack; supporting prose may still be English.

Declares a concrete type with fields and methods.

Aliases: class, struct

Syntax: 類型 <name> [<type-params>] <block>

Category#

type

Examples#

radix/corpus/genus/genus.fab (canonical · keyword)#

Declares a concrete type with fields and methods.

# =============================================================================
# 類型 — Declares a concrete type with fields and methods
# =============================================================================
#
# What this teaches:
#   • Declares a concrete type with fields and methods.
#   • Related keywords: 待實作介面, 實作
#
# Common mistakes:
#   • Using retired bare object literals (`{ key = expr }`) — use `GenusName { field = expr }` instead; bare `{ }` is now a JSON 值 literal.
#
# See also: 待實作介面, 實作
# =============================================================================

# Basic 類型 (record type) with fields
#
# 類型 <Name> {
#     <type> <property>
#     <type> <property> = <default>
# }
#
# GRAMMAR:
#   genusDecl :← '類型' ident '{' fieldDecl* '}'
#   instance  :← ident '{' fieldInit (',' fieldInit)* '}'
#
# EXPECTED OUTPUT:
#   Field values for Punctum and Persona instances (defaults and overrides).

class Punctum {
    var int x
    var int y
}

class Persona {
    var string 名稱
    # default when omitted at instantiation
    var int aetas = 0
    var bool activus = true
}

main {
    # Instantiate with all required fields
    const Punctum p ← Punctum { x = 10, y = 20 }
    print p.x
    print p.y

    # Instantiate with required + optional defaults
    const Persona marcus ← Persona { 名稱 = "Marcus" }
    print marcus.nomen
    # 0 from default
    print marcus.aetas
    # 真 from default
    print marcus.activus

    # Override defaults explicitly
    const Persona julia ← Persona { 名稱 = "Julia", aetas = 25, activus = false }
    print julia.nomen
    print julia.aetas
    print julia.activus
}

Expected output:

10
20
Marcus
0
verum
Julia
25
falsum