Guo
Guo

Reputation: 1813

How to transform this java code to scala?

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

Answers (1)

ch33hau
ch33hau

Reputation: 2961

To convert your code to scala, you could consider to:

  1. Use object to handle singleton
  2. Use Option[T] to handle null value

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

Update

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,

  1. For actual coding, I would prefer latter way.
  2. For dealing with null value, Option[T] would be a more desirable way, although it is not the best fit for this case.

Upvotes: 2

Related Questions