2017-05-17 125 views
0

可以任何一個解釋以下輸出。我有一個簡單的Scala代碼這樣的..scala中的伴隨對象

object compOrNotTest { 
    def main(args: Array[String]) { 
    var emp = new Employee("tom", 20) 
    println(emp) 
    println(Employee.adult(emp)) 
    Employee.printName("Roland", 38) 

    var emp2 = new Employee("Harry", 37) 
    Employee.printName(emp2) 
    } 
} 

class Employee(name: String, age: Int) { 
    val ageOfEmplyedd: Int = age 
    val nameEmp: String = name 

    override def toString() = this.name + " age : " + this.age 

    def printName() { 
    println("name is in Class " + nameEmp) 
    } 
} 

object Employee { 
    def adult(emp: Employee) = { 
    if (emp.ageOfEmplyedd > 18) 
     true 
    else 
     false 
    } 

    def printName(name: String, age: Int) = { 
    val emp1 = new Employee(name, age) 
    println("Name is : " + emp1.printName()) 
    } 

    def printName(emp1: Employee) = { 
    //val emp1 = new Employee(name, age) 
    println("Name is : "+ emp1.printName()) 
    } 
} 

而且我得到的輸出是

tom age : 20 
true 
name is in Class Roland 
Name is :() 
name is in Class Harry 
Name is :() 

我的問題是,爲什麼當我從同伴對象調用我只得到Name is :()。我期待像Name is : name is in Class Roland。請幫我理解在這種情況下scala是如何工作的。非常感謝

+0

爲什麼你認爲它應該是這個輸出? 只需把它放在一張紙上。 'Employee.printName(「Roland」,38)'它打出一個名字打印的命令,所以它會:'println(「Name is:」+ emp1.printName())', 它在那裏執行第一個'emp1 .printName()'打印出來的名字是Roland類「 ,然後剩下的:」Name is:()「。 – Rumid

+0

好的好吧,是的,我的壞....感謝很多,一些如何困惑.... – Biswajit

+0

@Biswajit我很高興我可以幫助。由於這個問題對於stackoveflow社區可能沒有用處(別人會遇到同樣的問題並且遇到這個問題的機會是什麼?:)),您可以考慮刪除它。 – Rumid

回答

2

返回類型Employee.printName(類別Employee)是Unit。這是因爲該功能使用過程語法聲明(函數聲明與它沒有=跡象,which has been deprecated並且將不再在未來版本的斯卡拉支持),其具有的Unit相關的返回類型。返回的Unit值在Scala中表示爲()

下面的函數聲明是等價的:

// Using (soon-to-be-deprecated) procedure syntax. 
def printName() { 
    println("name is in Class " + nameEmp) 
} 

// Using an explicit return type. 
def printName(): Unit = { 
    println("name is in Class " + nameExp) 
} 

// Using an inferred return type (note "=" in declaration). The last statement is the call 
// to println, which returns Unit, so a return type of Unit is inferred. 
def printName() = { 
    println("name is in Class " + nameExp) 
} 

如果你想返回已打印字符串,你需要這樣的事:

def printName() = { 
    val s = "name is in Class " + nameEmp 
    println(s) 
    s 
} 

或者,使用一個明確的回報類型,而不是從最後聲明推斷它:

def printName(): String = { 
    val s = "name is in Class " + nameEmp 
    println(s) 
    s 
} 
相關問題