简体   繁体   中英

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

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 trait s and class es, which are types, and object s, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM