Q:

How to use Option[T] to handle null value well in scala?

Java code:
public static Connection connection = null;
public static void main(String[] args) {
    if(connection == null){
        connection = ConnectionFactory.createConnection(conf);
    }
    //using connection object to do something
}

converting to Scala code:
someone tell me use Option[T] to handle null value, but I don't how to use Option[T] well, I think it very troublesome.
Scala code:
    var connOpt: Option[Connection] = None
    def main(args: Array[String]) {
        //check `connOpt` Option
        connOpt match {
            case Some(connection) => { /* using `connection` to do something-----code1  */    }
            case _ => {
                val connection = ConnectionFactory.createConnection()
                connOpt = Option(connection)
                // using `connection` to do something------code2
                }   
        }
    }

you can see scala code.

I need check connOpt always when I need use connOpt.
code1 and code2 is the same code, I need write two times, I know I can use function to package code1 or code2, but it's very troublesome.

How to handle this case?

A:

I think you can use the 'fold' method to do what you want like this
var connOpt:Option[Connection] = None
def main(args: Array[String]) {
    val connection = connOpt.fold(ConnectionFactory.createConnection()){conn => conn}
    //using connection object to do something
}

The logic of code mentioned above is the same as your java code that does not write the 'code1' and 'code2' two times.    
Using the following example to explain the usage of 'fold'
obj.fold{/*the obj is null, you can return the value you want*/}{a => a
/*if the obj is Some(value), the 'a' is just the 'value'*/
}

Good luck with you

