mrek
mrek

Reputation: 1888

Why Scala classes cannot have parameter of type object in contructor?

As far as I understood, object is simply singleton instance. I would like to create enumeration type with cell types, and then class Cell with constructor containing coordinates and enumeration type. However, it cannot be done, and I cannot find out why.

object CellType extends Enumeration {
  val Empty, X, O = Value
}

In another file:

class Cell(column: Int, row: Int, cellType : CellType) {
} // CellType is an object, and it doesn't work!

Do you have any ideas how to do it, or at least a reason why Scala forbids objects in contructors?

Error message:

Warning:(3, 37) imported 'CellType' is permanently hidden by definition of object CellType in package model import de.htwg.model.CellType

Upvotes: 1

Views: 211

Answers (1)

Cyrille Corpet
Cyrille Corpet

Reputation: 5315

CellType is not a type, it's an object. It is actually the only object of its type, CellType.type. If you want to have a function argument that can only be this object, you may use an argument of type CellType.type. But then, why even bother putting it as an argument, if it can only be CellType? Might as well use the object directly, not passing it as an argument.

What you probably want is not the type of CellType, but the type of its enumerated values, which happens to be CellType.Value.

NB: I personally found rather disturbing that the scala language defines on the same level traits and classes, which are types, and objects, which are instances of a singleton type. You should not be misguided by this apparent analogy, and really consider objects as values, and classes and traits as types.

Upvotes: 4

Related Questions