Classes: Difference between revisions

2,180 bytes added ,  5 months ago
m
→‎{{header|Wren}}: Changed to Wren S/H
imported>Arakov
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(2 intermediate revisions by 2 users not shown)
Line 1,181:
</syntaxhighlight>
=={{header|Elena}}==
ELENA 46.x :
<syntaxhighlight lang="elena">import extensions;
Line 3,771:
 
[[wp:Pecos_Bill|Context...]]
 
=={{header|Rhovas}}==
 
Rhovas has both structs and classes. [https://rhovas.dev/learn/tour/#structs Structs] are used for structured data (e.g. Kotlin data classes or Java records) however have some additional restrictions like fields always being part of the API (see earlier link).
 
An example of a struct for (<code>Decimal</code>) <code>Vector</code>s. Some notes:
* Fields are often mutable (<code>var</code>) and use mutability permissions to represent immutable structs rather than defining immutable fields directly.
* Methods are defined with a first parameter of <code>this</code>. The type is optional, but can be specified to support more nuanced subtypes as needed (e.g. with generics).
 
<syntaxhighlight lang="scala">
struct Vector {
var x: Decimal;
var y: Decimal;
 
func magnitude(this): Decimal {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
}
</syntaxhighlight>
 
The next step up from structs are classes. [https://rhovas.dev/learn/tour/#classes Classes] support the full range of Object-Oriented capabilities (e.g. encapsulation and inheritance) and are primarily for maintaining invariants.
 
For example, a hypothetical <code>UnitVector</code> class has an invariant between <code>x</code> and <code>y</code>, requiring a direction with non-zero magnitude. One option is to use a class to maintain that invariant:
* The example below uses immutable fields and validates the invariant in the constructor, but in practice there would be mutation involved.
* <code>require direct.x != 0.0 ...</code> validates preconditions for the direction <code>Vector</code>.
* <code>this { x: ..., y: ... };</code> initializes object fields in a single action to prevent partially constructed instances from being leaked (which would break invariants) and is less restrictive than similar constructors in Kotlin/Java.
 
<syntaxhighlight lang="scala">
class UnitVector {
val x: Decimal;
val y: Decimal;
 
init(direction: Vector) {
require direction.x != 0.0 || direction.y != 0.0;
val magnitude = direction.magnitude();
this { x: direction.x / magnitude, y: direction.y / magnitude };
}
}
</syntaxhighlight>
 
=={{header|Ring}}==
 
Line 4,430 ⟶ 4,470:
</pre>
=={{header|Wren}}==
<syntaxhighlight lang="ecmascriptwren">class Bear {
// Constructs a Bear instance passing it a name
// which is stored in the field _name
Line 4,457 ⟶ 4,497:
Growl!
</pre>
 
=={{header|X86-64 Assembly}}==
===UASM 2.52===
9,476

edits