The Item class has an instance variable id that starts with 0. I want to call nextID to increment the id from 0 to 1; however, when i do new Item().id += 1, there is a type mismatch. Why is that?
class Item { private var id: Int = 0 this.id = Item.nextId } // companion object object Item{ def apply() = new Item() def nextId: Int = { new Item().id += 1 //type mismatch } }
this.id = Item.nextId?+=returnsUnitso that's why you have a type mismatch, but that's not the only problem you have herenextIdis supposed to return anInt, but this expressionnew Item().id += 1returnsUnit, because that's what+=returns. Check this post for a possible solution: stackoverflow.com/questions/1888716/…. Moreover, I do not think you have to create a new Item insidenextId.