任何人都可以解释以下输出。我有一个像这样的简单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 : ()
我的问题是,为什么,当我从Companion对象调用时,我只得到Name is : ()
。我期待Name is : name is in Class Roland
之类的东西。请帮助我了解scala在这种情况下的工作原理。非常感谢
答案 0 :(得分:2)
Employee.printName
(在课程Employee
中)的返回类型为Unit
。这是因为此函数是使用过程语法(一个没有=
符号的函数声明which has been deprecated声明的,并且将来不再支持< em> Scala ),其关联的返回类型为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
}