2

How to extend an object in Scala with an abstract class that has a constructor, and apply method of the object returns the object as subtype of the abstract?

for example :

abstract class AbstractResource(amount:Int) {
    val amount:Int
    def getAmount = amount
}


case object Wood extends AbstractResource{
    def apply(amount: Int) = {
        // something that returns the subtype
   }
}

I think a good solution is:

abstract class AbstractResource {
    val amount: Int = 0

    def getAmount = amount
}


case object Wood extends AbstractResource {
    def apply(quantity: Int) = {
        new AbstractResource {
            override val amount = quantity
        }
    }
}

But my problem is I can't edit AbstractResource

8
  • Are you sure you don't want case class Wood(amount: Int) extends AbstractResource(amount)? Commented Aug 7, 2013 at 8:06
  • @TobiasBrandt Yes I don't want Commented Aug 7, 2013 at 8:13
  • Why does Wood have to extend AbstractResource? Note that the thing Wood#apply is returning is not of type Wood. Commented Aug 7, 2013 at 8:16
  • 3
    Well, then Wood must call the constructor of AbstractResource. I'm not sure what you're trying to achieve. Commented Aug 7, 2013 at 8:25
  • 1
    @Pooya How is this set of AbstractResource subtypes to be used? I have doubts that even your prototype solution is likely to achieve what you think it does, let alone what you actually need. Commented Aug 7, 2013 at 9:23

1 Answer 1

5

I have no idea why should Wood extend AbstractResource, but this works:

class AbstractResource(val amount:Int) {
  def getAmount = amount
}

case object Wood extends AbstractResource(0) {
  def apply(amount: Int) = {
    new AbstractResource(amount)
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think I should use a middle abstract class
@Pooya what is a middle abstract class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.