How to implement multiple constructor with different parameters in Scala

Using scala is just another road, and it just like we fall in love again, but there is some pain you will have to get, and sure we deserve that to achieve the goal we want.

In Scala, there is kind of constructors named auxiliary contructor, which have the special properties:

On the first line of the constructor’s body, call either another auxiliary constructor that has been declared before before it or the primary constructor.

That means if we want to implement the code in Java listed below:

class Test{

  private String name;

  private int age;

  public Test(String name){

     this.name = name;

  }

  public Test(String name, int age){

     this.name = name;

     this.age = age;

  }

}

We will have to write the scala code like this:

class Test(name :String, age :Int) {

  def this(name :String) = this(name, 0);

}

And it's OK, but how can we want to implement things like following:

[Java]

class Test{

   

  Test(String information){

   //parsing the information, and then set the name and age properties

   }

  Test(String name, int age){...}

}

OK, sure scala can handle this kind of boring thing, but how? You can have a test in scala, with the auxiliary constructor rule, you can do nothing like works in java. Because classes in scala always have a primary construtor, and it is the root constructor for each auxiliary one.

Answer is using object, the singleton Factory guy. Let's get to solve the problem using this great thing:

object Test {

  def apply(information :String) :Test = {

    //doing the parsing work, getting name and age

   //then return the instance

   new Test(name, age)

  }

}

With the help of object factory, you can create instance as :

val test = Test(information)

So it works, but then you have another situation, that you want create constructors as in Java:

class Test {

  Test(String a){...}

  Test(int b){...}

}

how can we handle this??

Just do if you think:

case class Test1(name :String)

case class Test2(age :Int)

object MainObject {

  def apply(name :String) :Test1 = new Test1(name)

  def apply(age :Int) :Test2 = new Test2(age) 

}

then you can create instance like:

val test1 = MainObject(name)

val test2 = MainObject(age)

and you can sure get fields from each variable, e.g: test1.name, or test2.age

"object" in scala is singleton, we should avoid sharing things in this kind of class.

 

转载于:https://www.cnblogs.com/ericchen/p/3427333.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值