scala - Scala 递归继承
问题描述
我正在浏览一些示例 scala 代码,但无法弄清楚代码的结果。
我尝试在代码中添加打印以了解代码流
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]
但实际输出是:hi [1]
这似乎递归不起作用。请帮助我理解它。
解决方案
推荐阅读
- r - 你如何循环 n 列并使用条件?
- python - 在 Python 中动态更改列名
- java - 通过 JNI NewObject 创建实例时 jvm.dll 中出现异常 0xC0000005
- c - 如何使用 gsasl gssapi 对 Active Directory 进行身份验证?
- python - 使用 Selenium webdriver 模块时 Firefox 浏览器无法打开
- python - 为什么在 for 循环中使用 yield
- asp.net - 从 asp.net 中的 bootstrap-datepicker 读取日期
- javascript - 页面通过表单验证后未重定向到条带结帐
- c# - 为什么这个本地接口引用超出范围?
- java - 韩语没有出现在 Apache Netbeans 中