Scala Listing and Reading

Scala Enumerationand the method Enumeration.Val readResolvedo not work as they should (possibly related to this entry in Scala trac ). Here is the program provided by * Steve Bendiola to illustrate the problem:

@serializable
object InvestmentType extends Enumeration {
  val Debt = Value("DEBT")
  val Future = Value("FUTURE")
  val Equity = Value("EQUITY")
}

Now there is a class Mainthat can be launched either using arument W, where it will write the enumeration values ​​to a file, or Rwhere it will read them again:

object Main {
  def main(args: Array[String]) = {
    args(0) match {
      case "R" => {
        val ois = new ObjectInputStream(new FileInputStream("enum.ser"))
        var obj: Object = null

        foreach(ois) { obj =>
              obj match {
                case InvestmentType.Debt => println("got " + obj)
                case InvestmentType.Equity => println("got " + obj)
                case InvestmentType.Future => println("got " + obj)
                case _ => println("unknown: " + obj + " of: " + obj.getClass)
              }
        }
      }

      case "W" => {
        val oos = new ObjectOutputStream(new FileOutputStream("enum.ser"))
        InvestmentType.foreach {i => oos.writeObject(i)}
        oos.flush
        oos.close
      }
    }
  }

Both of these methods require this method foreach:

  def foreach(os: ObjectInputStream)(f: Object => Unit) {
    try {
      val obj = os.readObject
      if (obj != null) {
        f(obj)
        foreach(os)(f)
      }
    } catch {
      case e: EOFException => //IGNORE
    }
  }
}

The output of this program should not look like this:

got DEBT
unknown: FUTURE of: class scala.Enumeration$Val
unknown: EQUITY of: class scala.Enumeration$Val

This seems to be due to the order announced. Reordering them, it seems that the first value is always reasonably resolved

+3
source share
1

Scala hashCode Value Enumeration , . . :

object InvestmentType extends Enumeration {
  val Debt = Value(1, "DEBT")
  val Equity = Value(2, "EQUITY")
  val Future = Value(3, "FUTURE")
}

, , .

.

+1

Source: https://habr.com/ru/post/1716768/


All Articles