请帮助我理解。
我的问题:
我在类构造函数中有N个参数(查看下面的Email类),
1.如何创建多个辅助构造函数?
2.如何将方法值传递给构造函数参数?
class Email (
private val firstName: String,
private val lastName: String,
private val domain: String,
private var emailCapacity,
private var alterEmail,
private var chngPassword){
....
}
答案 0 :(得分:1)
我想通过"辅助构造函数"你的意思是重载 - 在这种情况下,你可以为某些参数提供默认值,例如。
class Email (
private val firstName: String,
private val lastName: String,
private val domain: String,
private val emailCapacity=100,
private val alterEmail=false,
private val chngPassword=true)
然后您可以像val em=new Email("a","b","mydomain.com",alterEmail=true)
答案 1 :(得分:0)
您还可以按如下方式创建辅助构造函数:
class Email private (firstname: String, lastName: String, domain: String, emailCapacity: String, alterEmail: String, chgpassord: String) {
def this(firstname: String) = this(firstname, "", "", "", "", "")
}
如果您想降低灵活性并仅允许特定的构造函数,这可能有意义。