过去几天我一直在研究Vala编程语言,看起来很有希望。但是,我无法弄清楚如何在对象构造中正确分配常量(当前Vala等效于final
)。例如,在Java中:
import java.lang.Math;
public class Rectangle {
public final double sideA;
public final double sideB;
public final double area;
public final double diagonal;
public Rectangle (double SideA, double SideB) {
sideA = SideA;
sideB = SideB;
area = SideA * SideB;
diagonal = Math.sqrt(Math.pow(SideA, 2) + Math.pow(SideB, 2));
}
}
如何在Vala中编写?
答案 0 :(得分:1)
Vala与Java的final关键字没有直接对应关系。我认为你最接近的就是这样:
public class Rectangle : GLib.Object {
public double sideA { get; construct; }
public double sideB { get; construct; }
public double area { get; construct; }
public double diagonal { get; construct; }
public Rectangle (double SideA, double SideB) {
GLib.Object (
sideA: SideA,
sideB: SideB,
area: SideA * SideB,
diagonal: Math.sqrt(Math.pow(SideA, 2) + Math.pow(SideB, 2)));
}
}
构造属性与final有点不同,很大程度上是因为GObject构造的工作原理。它们只能在构造时设置,但不像Java中的final(IIRC ......我的大部分Java知识都被压缩),它们也可以在构造期间由子类设置。例如,这是完全可以接受的:
public class Square : Rectangle {
public Square (double Side) {
GLib.Object (
sideA: Side,
sideB: Side,
area: Side * Side,
diagonal: Math.sqrt(Math.pow(Side, 2) + Math.pow(Side, 2)));
}
}
所以,如果你想允许GObject风格的构造(如果你正在制作一个其他人会调用的库,我会建议你这样做...如果代码只适合你而没有必要),你可能想要做更像这样的事情:
public class Rectangle : GLib.Object {
public double sideA { get; construct; }
public double sideB { get; construct; }
private double? _area = null;
public double area {
get {
if ( _area == null )
_area = sideA * sideB;
return _area;
}
}
private double? _diagonal = null;
public double diagonal {
get {
if ( _diagonal == null )
_diagonal = Math.sqrt(Math.pow(sideA, 2) + Math.pow(sideB, 2));
return _diagonal;
}
}
public Rectangle (double SideA, double SideB) {
GLib.Object (
sideA: SideA,
sideB: SideB,
area: SideA * SideB,
diagonal: Math.sqrt(Math.pow(SideA, 2) + Math.pow(SideB, 2)));
}
}