首页 > 解决方案 > 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]

这似乎递归不起作用。请帮助我理解它。

标签: scala

解决方案


推荐阅读