Vala - 对象构造函数中的常量初始化和赋值
过去几天我一直在研究 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中该怎么写?
I've been looking at the Vala programming language over the past few days, and it looks promising. However, I can't figure out how to properly assign a constant (currently the Vala equivalent to final
) in object construction. For example, in 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));
}
}
How would this be written in Vala?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Vala 没有与 Java 的 Final 关键字直接等效的关键字。我认为您能得到的最接近的结果是这样的:
构造属性与最终属性有点不同,很大程度上是因为 GObject 构造的工作方式。它们只能在构造时设置,但与Java中的final不同(IIRC...我的大部分Java知识都被压抑了)它们也可以在子类构造期间设置。例如,这是完全可以接受的:
所以,如果您想允许 GObject 风格的构造(如果您正在制作一个其他人会调用的库,我建议您这样做......如果代码只适合您,则不需要),你可能想做更多类似这样的事情:
Vala doesn't have a direct equivalent of Java's final keyword. I think the closest you are going to be able to come is something like this:
construct properties are a bit different from final, largely because of how GObject construction works. They can only be set at construct time, but unlike final in Java (IIRC... most of my Java knowledge has been repressed) they can also be set during construct by a subclass. For example, this is perfectly acceptable:
So, if you want to allow GObject-style construction (which I would suggest you do if you are making a library other people will call... if the code is just for you there is no need), you might want to do something more like this: