I am making a javaFX class and I need one of the variables to be initialized in order for it to work (in my progr开发者_如何学Cam there's no default value I can use). This is the best I've come up with, but I'd like something that wont compile unless you initialize the variable.
Example Class:
Public class Class1{
public-init var var1:String;
postinit{
if(var1 == null){
println("You need to initialize var1");
}
}
I'd call it like this:
var object1 = Class1{var1:"input"};
How can I prevent it from compiling if I do this?
var object1 = Class1{};
Unfortunately, I think you have the best solution for forcing initialization. Only other thing you can do is set a default value:
public var var1: String = "BOGUS";
You can use this:
public class Class1 {
public var var1: String = "" on replace{
if (var1 == null) {
var1 = "";
}
};
}
var object1 = Class1{};
println(object1.var1);
object1.var1="HOLA :)";
println(object1.var1);
Output:
Mundo
HOLA
:)
Or maybe:
public class Class1 {
public-init var var1: String;
init {
if (var1 == null) { //or var1. length() == 0 ) {
println("You need to initialize var1");
Stage {
title: "Ups!!!"
onClose: function() {
}
scene: Scene {
content: [
Label {
text: "You need to initialize var1"
}
]
}
}
}
}
}
精彩评论