Я рассматриваю какой-то пример скала-кода и не могу выяснить результат этого кода.
Я попытался добавить отпечатки в код, чтобы понять поток кода
abstract class MyList {
/*
1. head -> returns the first element
2. tail -> returns the remaining elements
3. isEmpty -> is the list empty
4. add(int) -> new list with this element added
5. toString -> a string representation of this list
*/
def head: Int
def tail: MyList
def isEmpty: Boolean
def add(element: Int): MyList
def printElements: String
override def toString: String = "[" + printElements + "]"
}
object Empty extends MyList {
def head: Int = throw new NoSuchElementException
def tail: MyList = throw new NoSuchElementException
def isEmpty: Boolean = true
def add(element: Int): MyList = new Cons(element, this)
def printElements: String = ""
}
class Cons(val h: Int, val t: MyList) extends MyList {
def head: Int = h
def tail: MyList = t
def isEmpty: Boolean = true
def add(element: Int): MyList = new Cons(element, this)
def printElements: String = {
if(t.isEmpty) {
println("hi")
"" + h
}
else {
println(h)
h + " " + t.printElements
}
}
}
object ListTest extends App {
val my_list = new Cons(1, new Cons(2, new Cons(3, Empty)))
println(my_list.toString)
}
Мой ожидаемый результат:
1
2
3
[1 2 3]
Но фактический результат:
Привет
[1]
Кажется, рекурсия не работает. Пожалуйста, помогите мне понять это.