假設我有2個文件。Scala類:創建新實例時避免參數
- myMainApplication.scala
- printInfos.scala
簡言之myMainApplication.scala包含
val name = "blah"
val age= 45
簡單地說我的課myMainApplication.scala應打印出的姓名和年齡通過創建新的printInfos實例。但是,我不應該在創建實例時添加任何參數。
我想什麼來避免:
內printInfos.scala
class printInfos(val myName: String,
val myAge: Int
val myLoc: String
val myNPP: Double
val myCountry: String
val myProvice: String
val myNPAP: String) {
def printInfos() = {
println("Your method printInfos print out" + myName + myAge + myLoc + myNPP + myCountry + myProvice + myNPAP)
}
}
內myMainApplication.scala
val name = "blah"
val age= 45
val loc = "blah"
val npp = 45.5
val country = "germany"
val province = "bayern"
val npap = "blaha"
// want to avoid to enter so many params
val printInfoInstance = new printInfos(name, age, loc, npp, country, province, npap)
printInfoInstance.printInfos()
我想獲得somethi NG類似:
內printInfos.scala
class printInfos() {
var myName: String = 0
var myAge: Int = 0
var myLoc: String = 0
var myNPP: Double = 0
var myCountry: String = 0
var myProvice: String = 0
var myNPAP: String = 0
def printInfos() = {
println("Your method printInfos print out" + myName + myAge + myLoc + myNPP + myCountry + myProvice + myNPAP)
}
}
內myMainApplication.scala
// want to create new instance with no params at begining
val printInfoInstance = new printInfos()
val name = "blah"
printInfoInstance.myName() = name
val age= 45
printInfoInstance.myAge() = age
val loc = "blah"
printInfoInstance.myLoc() = loc
val npp = 45.5
printInfoInstance.myNPP() = npp
val country = "germany"
printInfoInstance.myCountry() = country
val province = "bayern"
printInfoInstance.myProvice() = province
val npap = "blaha"
printInfoInstance.myNPAP() = npap
printInfoInstance.printInfos
尋找改進
會得到它可能小號類似於第二個建議,但避免使用變種?但是,的最終目標仍然是在創建新實例時避免添加大量參數。
這可能有幫助:http://docs.scala-lang.org/tutorials/tour/default-parameter-values.html – maasg