如何将这个java代码转换为scala?

时间:2016-05-10 09:25:21

标签: scala

我不知道如何在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;
    }
}

1 个答案:

答案 0 :(得分:2)

要将代码转换为scala,您可以考虑:

  1. 使用object处理singleton
  2. 使用Option[T]处理null
  3. 这是一个想法:

    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()
            }
        }
    }
    

    我的

    1. 对于实际编码,我更喜欢后一种方式。
    2. 为了处理null值,Option[T]将是一种更理想的方式,尽管它不适合这种情况。