如何将此java代码转换为scala?

如何将此java代码转换为scala?,scala,Scala,我不知道如何在scala中使用null值,以及如何在scala中初始化代码(因为java中有构造函数),我需要一个帮助我理解的示例 public class HBaseTest { private Configuration conf = null; private Admin admin = null; protected static Connection connection = null; private static final HBaseTest HB

我不知道如何在scala中使用
null
值,以及如何在scala中初始化代码(因为java中有构造函数),我需要一个帮助我理解的示例

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;
    }
}

将代码转换为<代码> Scala < /C> >,可以考虑:

  • 使用
    object
    处理
    singleton
  • 使用
    选项[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]
    将是一种更理想的方法,尽管它不是最适合这种情况

  • 为什么连接既受
    保护
    又受
    静态保护
    ?在我看来,这就像是一次单例尝试。有什么理由让
    会员受到保护吗?非常感谢!这对我很有用!您可以使用scala.util.Try获得getAdmin方法的结果,并将admin改为val而不是var.Hi@krynio,同意您的看法,scala.util.Try可以使代码更整洁、更好。我将更新代码,但仍然保留现有代码,因为它解决了核心问题,即
    scala
    中的
    null
    值。谢谢你的建议!