0

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 } } 
6
  • Why are you doing this this.id = Item.nextId? Commented Apr 11, 2017 at 0:07
  • I think += returns Unit so that's why you have a type mismatch, but that's not the only problem you have here Commented Apr 11, 2017 at 0:07
  • @nbro This is actually my homework assignment. According to the instruction i should create a private static nextId variable that stores the next available id number. The Item constructor could use this to initialize id, then increment the variable. Scala doesn't have static variables. So I declared nextId in the Item companion object. Commented Apr 11, 2017 at 0:11
  • @2rs2ts Can you point out the other problems I have? Commented Apr 11, 2017 at 0:12
  • @user21478621 I'm not sure, but nextId is supposed to return an Int, but this expression new Item().id += 1 returns Unit, 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 inside nextId. Commented Apr 11, 2017 at 0:27

1 Answer 1

2

Where to begin?

def nextId: Int = { new Item().id += 1 } 

+= is an assignment. Assignments don't have return values but nextId is supposed to be an Int. We might fix it like this...

def nextId: Int = { val nitem = new Item() nitem.id += 1 nitem.id } 

...but there are other problems. Every time someone invokes nextId it creates a new Item, that Item's id is incremented, the updated value of this id is returned, and the new Item is thrown away. That doesn't sound right.

class Item { private var id: Int = 0 this.id = Item.nextId } 

Hmm, this looks suspicious. When an Item is created it calls nextId, but nextId creates a new Item, which is going to call nextId, which creates a new Item, which calls .... where will it all end?

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for pointing it out! When I was doing nextId, I am not sure how I can mutate the id in Item without creating a new Item. Do you have any hints for me how to fix this?
Make the instance id a val. Initialize it to the only value it will ever have when it is created. The companion object should hold the private var that is the id counter. Then all that nextId() has to do is increment the counter and return the new value.
Thank you so much :) That helps a lot!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.