Scala:class 对象列表打印 class variable/attributes

Scala: List of class objects printing the class variable/attributes

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

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
    }


}

假设您的代码看起来像这样向 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 中案例 类 的变量,您可以将 foreach 声明为

inventory_storage.foreach{
  x => println(x.inventory_item_name)
}