Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does scala.Enumeration.nextName get the identifier text?

Tags:

scala

scala.js

scala.Enumerator.nextName and .nextNameOrNull currently read:

/** The string to use to name the next created value. */
protected var nextName: Iterator[String] = _

private def nextNameOrNull =
  if (nextName != null && nextName.hasNext) nextName.next() else null

nextNameOrNull is subsequently called to get the name to use for the item being created in the Enumeration.

How does this code actually achieve this?

When I copy-paste it into a simple example:

class MyBaseClass extends Serializable {
  /** The string to use to name the next created value. */
  protected var nextName: Iterator[String] = _

  private def nextNameOrNull =
    if (nextName != null && nextName.hasNext) nextName.next() else null

  protected final def Value(): Val = Val(nextNameOrNull)

  case class Val(name:String)
}

object MyObject extends MyBaseClass {
  val myValue = Value

  println("Hello from MyObject, myValue: " + myValue)
}

it prints: Hello from MyObject, myValue: Val(null) instead of the hoped for Val(myValue)

What do I need to add to make it work?

like image 216
Jxtps Avatar asked Mar 17 '23 14:03

Jxtps


1 Answers

In Scala JVM, Enumeration uses reflection to get the name of the val to which a Value was assigned to if nextNameOrNull returns null.

In Scala.js, we do not have this luxury (no reflection support). Therefore, the Scala.js compiler special cases scala.Enumeration, so that code that uses it can work.

If you want to implement some method that knows the name of the val it is assigned to, have a look at sbt's project macro. Scala's Enumerations could have been implemented that way starting 2.10, but are older.

like image 72
gzm0 Avatar answered Mar 19 '23 02:03

gzm0