Scala:打印类变量/属性的类对象列表

时间:2018-10-29 17:57:10

标签: scala list class oop instance

我正在尝试打印存储在列表中的类实例的变量。应该自动生成一个吸气方法供我使用,但是我不能使用它。

case class InventoryItem(var inventory_item_name: String, var 

number_of_available_items: Int)

    class InventoryManagement() {


    private var inventory_storage = new ListBuffer[InventoryItem]()


    //New function that connects list to the front.
    def attachToList(): Unit = {}

    //////////////////////////////
    //ADDING AN ITEM TO THE LIST//
    //////////////////////////////
    def addItems(): Unit = {
      var inventory_item_name_input = "0"
      var number_of_available_items_input = "0"
      inventory_item_name_input = scala.io.StdIn.readLine("What is the name of the item you want to add?")
      number_of_available_items_input = scala.io.StdIn.readLine("How many are there?")
      inventory_storage += new InventoryItem(inventory_item_name_input,number_of_available_items_input.toInt)
    }
    ///////////////////
    //PRINT THE LIST //
    ///////////////////
    def listItems(): Unit = {
      println(); println();
      println(inventory_storage)
      println(inventory_storage.InventoryItem.inventory_item_name) // Failure
      println(inventory_storage.inventory_item_name) // Failure
      inventory_storage.foreach(println(inventory_item_name)) // More Failure
    }


}

1 个答案:

答案 0 :(得分:0)

让我们说您的代码看起来像这样,将元素添加到ListBuffer。

case class InventoryItem(var inventory_item_name: String, var number_of_available_items: Int)

var inventory_storage = new ListBuffer[InventoryItem]()

inventory_storage += InventoryItem("a1",1)
inventory_storage += InventoryItem("a2",2)
inventory_storage += InventoryItem("a3",3)
inventory_storage += InventoryItem("a4",4)

现在要访问listBuffer内的case类的变量,您可以声明将您的foreach写为

inventory_storage.foreach{
  x => println(x.inventory_item_name)
}
相关问题