访问(/导入)Scala枚举

时间:2014-05-15 21:15:38

标签: scala enumeration

对于以下HwLogger.PersisterType枚举:

object HwLogger extends Serializable {

  object PersisterType extends Enumeration {
    type Persisters = Value
    val FilePersister, HdfsPersister, SocketPersister = Value
  }

} 

在配套课程中 - 我们如何访问它?请注意下面的大量进口..

class HwLogger extends Serializable {
  import collection.mutable.ArrayBuffer
  import HwLogger.PersisterType._
  import HwLogger.PersisterType
  var persisterTypes = ArrayBuffer[PersisterType]()   // Compiler says " error: not found: type PersisterType"
  def setDefaults : Unit = {
    import PersisterType._
    persisterTypes ++ FilePersister ++ HdfsPersister 
  }

}

UPDATE 在接受的答案(以及arraybuffer附加运算符的语法修正)之后,这里是更正后的代码:

object HwLogger extends Serializable {

  object PersisterType extends Enumeration {
    type Persisters = Value
    val FilePersister, HdfsPersister, SocketPersister = Value
  }

}

class HwLogger extends Serializable {
  import collection.mutable.ArrayBuffer
  import HwLogger.PersisterType._
  import HwLogger.PersisterType
  var persisterTypes = ArrayBuffer[Persisters]()    // This is the fix (Persisters instead of PersisterType)
  def setDefaults : Unit = {
    import PersisterType._
    persisterTypes :+ FilePersister :+ HdfsPersister
  }

}

**另一次更新**

更改枚举对象将避免麻烦:

object HwLogger extends Serializable {

  object PersisterType extends Enumeration {
    type PersisterType = Value    // Changed the "type" to be same as object name
    val FilePersister, HdfsPersister, SocketPersister = Value
  }

}

class HwLogger extends Serializable {
  import collection.mutable.ArrayBuffer
  import HwLogger.PersisterType._
  import HwLogger.PersisterType
  var persisterTypes = ArrayBuffer[PersisterType]()    // Revert back to PersisterType
  def setDefaults : Unit = {
    import PersisterType._
    persisterTypes :+ FilePersister :+ HdfsPersister
  }

}

1 个答案:

答案 0 :(得分:3)

枚举中的元素类型为Persisters,而不是PersisterTypePersisterType只是一个值。您需要导入PersisterType内的类型和值才能使用Enumeration

class HwLogger extends Serializable {
  import collection.mutable.ArrayBuffer
  import HwLogger.PersisterType._
  val persisterTypes = ArrayBuffer[Persisters]()
  def setDefaults: Unit = {
    persisterTypes += FilePersister += HdfsPersister 
  }
}