Home > Blockchain >  Is there a way to get all possible protobuf Enum values using scalapb?
Is there a way to get all possible protobuf Enum values using scalapb?

Time:12-07

I have a protobuf enum like

enum MyEnum {
A = 0;
B = 1; 
C = 2;
}

At runtime, I want to loop over all possible values for the enum like this:

MyEnum().uniqueValues.forEach(println)

How might I do this with scalapb or just in scala?

CodePudding user response:

if you use scalapb with default settings, a following protobuf enumeration type

enum MyEnum {
  A = 0;
  B = 1; 
  C = 2;
}

will be converted into an abstract class with a companion object

sealed abstract class MyEnum(val value: _root_.scala.Int) extends _root_.scalapb.GeneratedEnum 
???
object MyEnum extends _root_.scalapb.GeneratedEnumCompanion[MyEnum]

And the companion object MyEnum will be providing method values you need

lazy val values = scala.collection.immutable.Seq(A, B, C)

So, you can access it via MyEnum.values or via MyEnum.A.companion.values

  • Related