The Scala code is below:
abstract class Human {
def call
}
class Student(val name: String) extends Human {
override def call = "\"" + name + "\""
}
object MyApp extends App {
var s:Student = new Student("robin")
println(s.call)
}
But the output of this section of code is:
()
Nothing, just a pair of parenthesis. What happen? Why doesn’t Scala use the ‘call’ function in subclass ‘Student’?
The answer is: we forget to define the return Type of function ‘call’, so its default return Type is ‘Unit’. The value of ‘Unit’ is only ‘()’. Hence no matter what value we give to ‘call’, it only return ‘()’.
We just to add return Type:
abstract class Human {
def call: String
}
......
It print “robin” now.