Home > Software design >  How to convert set/println to string?
How to convert set/println to string?

Time:03-23

I'm trying to add set to email as text

//Data class

@Entity(tableName = "inventory")
data class InventoryDataClass(
    @PrimaryKey(autoGenerate = true)
    var id: Int,
    @NonNull var itemNumber: String,
    @NonNull val itemDescription: String,
    val currentInventory: Int?,
    @NonNull val optimalInventory: Int,
    @NonNull val minInventory: Int
)

// getting list from room

    val inventoryList by mainViewModel.getInventoryItems.collectAsState(initial = emptyList())

//converting list to set

val emailNumber = inventoryList.map { item ->
println("Item Number: ${item.itemNumber} | Item Description: ${item.itemDescription} | Current Inventory: ${item.currentInventory.toString()}")}.toSet()

I'm able to get the output I need:

I/System.out: Item Number: 123| Item Description: item1 | Current Inventory: 47
I/System.out: Item Number: 456| Item Description: item2 | Current Inventory: 8
...

How can I get it as a string and add it to my email as text? So far i'm only able to get Kotlin.Unit

Log.d(TAG, "InventoryMainScreen: $emailNumber")
//output
D/MainActivity: InventoryMainScreen: [kotlin.Unit]

CodePudding user response:

You can append to a StringBuilder:

//Output this:
//Item Number: 123| Item Description: item1 | Current Inventory: 47
//Item Number: 123| Item Description: item1 | Current Inventory: 47

val emailNumber = StringBuilder()
inventoryList.forEach { item ->
    emailNumber.append("Item Number: ${item.itemNumber} | Item Description: ${item.itemDescription} | Current Inventory: ${item.currentInventory}").append("\n")
}
emailNumber.removeSuffix("\n")

CodePudding user response:

You can use joinToString:

val logsString = inventoryList.joinToString(separator = "\n") { item ->
    "Item Number: ${item.itemNumber} | Item Description: ${item.itemDescription} | Current Inventory: ${item.currentInventory.toString()}"
}
  • Related