// FormatGroceryItemsList Example // Run this example on the Kotlin Playground Webpage at // https://play.kotlinlang.org // Remove or comment out example outputs before running. //********************************* // Example A. Load GroceryItem data // into MutableList collection. //********************************* // Grocery items entered from TextField // and read into these variables. var desc = "Peanuts" var code = "24680" var price = "2.99" // Create mutable list. In an app, // is a state variable. var groceryList = mutableListOf( ) // Load grocery items into list. var groceryItem = "($desc;$code;$price)" groceryList.add(groceryItem) // Add another item. desc = "Cashews" code = "32435" price = "2.99" groceryItem = "($desc;$code;$price)" groceryList.add(groceryItem) // Look at current items in list. println(groceryList.toString( )) println( ) // Output: [(Peanuts;24680;2.99), (Cashews;32435;2.99)] // Grocery items in this format can be stored // in a file. //********************************* // Example B. Format GroceryItem data // from MutableList to display string, for // example in a Text element. //********************************* // Sample values of items in mutableList: //[(Peanuts;24680;2.99), (Cashews;32435;2.99)] var display = "" for(item in groceryList) { val cleaned = item.removeSurrounding("(", ")") val itemArray = cleaned.split(";") display += "Description: ${itemArray[0]}\n" + "Code: ${itemArray[1]}\n" + "Price: ${itemArray[2]}\n\n" } println(display) // Output: Description: Peanuts Code: 24680 Price: 2.99 Description: Cashews Code: 32435 Price: 2.99 //**************************************** // Example C. Load list toString formatted // formatted data from file back into list. //**************************************** var formatted = "[(Peanuts;24680;2.99), (Cashews;32435;2.99)]" groceryList.clear( ) formatted = formatted.removeSurrounding("[", "]") val groceryArray = formatted.split(",") for(item in groceryArray) { groceryList.add(item.trim( )) } println(groceryList)