2 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超13個(gè)贊
類(lèi)名后面沒(méi)有參數(shù)就是無(wú)參的:
1 2 3 4 5 | class mytest { val i=100 val s="my name" } val m=new mytest |
有參數(shù),但是每個(gè)參數(shù)都有默認(rèn)值的構(gòu)造器,也可以看成支持無(wú)參的
也可以寫(xiě)一個(gè)輔助構(gòu)造器,是無(wú)參的
1 2 3 4 5 | class mytest2(val x:Int) { val s="my name" def this() = this(100) } val m2 = new mytest2 |

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超8個(gè)贊
直接寫(xiě)到類(lèi)的里面就可以了:
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代碼基本等價(jià)于下面的Java代碼:
public class A {
public A() {
//do anything you want
println("Hi, the construtor invoked here..");
}
}
- 2 回答
- 0 關(guān)注
- 853 瀏覽
添加回答
舉報(bào)