[英]Companion objects in scala
can any one explain the following output. 谁能解释以下输出。 I have a simple Scala code like this..
我有一个像这样的简单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())
}
}
And the output I am getting is 我得到的输出是
tom age : 20
true
name is in Class Roland
Name is : ()
name is in Class Harry
Name is : ()
My question is that why , when I am calling from Companion object I am getting only Name is : ()
. 我的问题是,为什么当我从Companion对象调用时,我只得到
Name is : ()
。 I am expecting something like Name is : name is in Class Roland
. 我期望类似
Name is : name is in Class Roland
。 Please help me out to understand the how scala works in this case. 请帮助我了解Scala在这种情况下的工作方式。 Thanks a lot
非常感谢
The return type of Employee.printName
(in class Employee
) is Unit
. Employee.printName
的返回类型(在Employee
类中)是Unit
。 This is because this function was declared using procedure syntax (a function declaration with no =
sign in it, which has been deprecated and which will no longer be supported in a future version of Scala ) that has an associated return type of Unit
. 这是因为此函数是使用过程语法声明的(具有不带
=
符号的函数声明,该函数声明已被弃用 ,并且在以后的Scala版本中不再支持),并且具有关联的返回类型Unit
。 The Unit
value that is returned is represented in Scala as ()
. 在Scala中,返回的
Unit
值表示为()
。
The following function declarations are equivalent: 以下函数声明是等效的:
// 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)
}
If you wanted to return the string that was printed, you would need something like this: 如果要返回已打印的字符串,则需要类似以下内容:
def printName() = {
val s = "name is in Class " + nameEmp
println(s)
s
}
Or, using an explicit return type, instead of inferring it from the last statement: 或者,使用显式返回类型,而不是从最后一条语句推断出它:
def printName(): String = {
val s = "name is in Class " + nameEmp
println(s)
s
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.