views:

40

answers:

3

I am making a javaFX class and I need one of the variables to be initialized in order for it to work (in my program 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{};
+1  A: 

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";
Eric Wendelin
It occurs to me that I could throw an exception if the variable is not initialized. While that's still post-compile, it is at least a louder complaint.
Kyle
+1  A: 

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
 :)
rsa
A: 

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"
                        }
                    ]
                }
            }
        }
    }

}

alt text

rsa