我不知道如何在scala中使用null
值,以及如何在scala中初始化代码(因为java中有构造函数),我需要一个示例帮助我理解。< / p>
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;
}
}
答案 0 :(得分:2)
要将代码转换为scala
,您可以考虑:
object
处理singleton
Option[T]
处理null
值这是一个想法:
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
}
}
}
@krynio建议,可以使用scala.util.Try
改进代码,如下所示:
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()
}
}
}
我的,
null
值,Option[T]
将是一种更理想的方式,尽管它不适合这种情况。