为了账号安全,请及时绑定邮箱和手机立即绑定

scala怎么定义无参构造函数

scala怎么定义无参构造函数

动漫人物 2019-05-31 19:02:05
scala怎么定义无参构造函数
查看完整描述

2 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

类名后面没有参数就是无参的:

1

2

3

4

5

class mytest {       

  val i=100

  val s="my name"

}

val m=new mytest

有参数,但是每个参数都有默认值的构造器,也可以看成支持无参的

也可以写一个辅助构造器,是无参的

1

2

3

4

5

class mytest2(val x:Int) {

  val s="my name"

  def  this()  = this(100)

}

val m2 = new mytest2

   

 




查看完整回答
反对 回复 2019-06-01
?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

直接写到类的里面就可以了:

scala> class A {
| //do anything you want
| println("Hi, the construtor invoked here..")
| }
defined class A

scala> val a = new A
Hi, the construtor invoked here..
a: A = A@1339a0dc

scala>

上面的Scala代码基本等价于下面的Java代码:

public class A {
public A() {
//do anything you want
println("Hi, the construtor invoked here..");
}
}




查看完整回答
反对 回复 2019-06-01
  • 2 回答
  • 0 关注
  • 766 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信