Reputation: 1813
I don't know how to use null
value in scala, and how to initialize the code in scala (because there is the constructor in java), I need an example helped me to understand.
public class HBaseTest {
private Configuration conf = null;
private Admin admin = null;
protected static Connection connection = null;
private static final HBaseTest HBaseTest = new HBaseTest();
public static final String ZK_PARAMS = "192.168.1.20:2181";
public static final String HBASE_ROOTDIR = "hdfs://192.168.1.20:8020/hbase";
/**
* initialization
*/
private HBaseTest() {
conf = new Configuration();
conf.set("hbase.zookeeper.quorum", ZK_PARAMS);
conf.set("hbase.rootdir", HBASE_ROOTDIR);
try {
admin = ConnectionFactory.createConnection(conf).getAdmin();
} catch (Exception e) {
e.printStackTrace();
}
}
public static HBaseTest getInstance() {
return HBaseTest;
}
}
Upvotes: 1
Views: 82
Reputation: 2961
To convert your code to scala
, you could consider to:
object
to handle singleton
Option[T]
to handle null
valueHere is the idea:
object HBaseTest {
val conf: Configuration = new Configuration()
var admin: Option[Admin] = None
// some other code...
try {
admin = admin = ConnectionFactory.createConnection(conf).getAdmin()
} catch {
case e: Exception => e.printStackTrace()
}
// to use `admin`, it could be in other methods
// here is the idea on how to determine whether it is None
admin match {
case Some(a) => {
// call a to do something
}
case _ => {
// admin is None, handle it
}
}
}
Suggested by @krynio, the code could be improved by using scala.util.Try
as below:
import scala.util.{Try, Success, Failure}
object HBaseTest {
val conf: Configuration = new Configuration()
val getAdmin: Try[Admin] = Try(ConnectionFactory.createConnection(conf).getAdmin())
// some other code...
// admin will be wrapped in either Success(admin) or Failure(e)
getAdmin match {
case Success(admin) => {
// call admin to do something
}
case Failure(e) => {
// handle exception, eg, e.printStackTrace()
}
}
}
My thoughs,
null
value, Option[T]
would be a more desirable way, although it is not the best fit for this case.Upvotes: 2