Search code examples
javascalasprayspray-dsl

Scala symbol to java enum


I am using a spray-routing which is pretty elegant with using symbols for parameters. However I am dealing with some legacy code and need to use java enum. Is there some elegant way how to convert scala symbol to java enum?

So the desired code would look as follows:

      post {
        parameters(('adId.as[String], 'propertyType.as[TypNe])).as(Import) { imp:Import =>
          complete {
            adImporterService ! imp
            StatusCodes.Accepted
          }
        }

where TypNem is java enum and Import is a scala case class. Instead of

      post {
        parameters(('adId.as[String], 'propertyType.as[String])) { (aId,pType) =>
          complete {
            adImporterService ! Import(aId,TypNe.valueOf(pType.toUpperCase()))
            StatusCodes.Accepted
          }
        }
      }

Solution

  • For Java Enum PropertyType

    public enum PropertyType {
        AAA, BBB, CCC
    } 
    

    You need to provide custom Deserializer

      implicit val propertyTypeDeserializer = 
        new Deserializer[String, PropertyType] {
          def apply(s: String): Deserialized[PropertyType] = {
            Try(PropertyType.valueOf(s)) match {
              case Success(pt) => 
                 Right(pt)
              case Failure(err) => 
                 Left(MalformedContent("Wrong property type. Accepted values: ${PropertyType.values}", Some(err)))
            }
          }
        }
    
      def receive: Receive = runRoute {
        path("test") {
          parameter('prop.as[PropertyType]) { case prop =>
            get {
              complete(s"Result: $prop. Class: ${prop.getClass}")
            }
          }
        }
      }
    

    Solution from @Dici also works and much smaller, but with custom Deserializer you are more flexible with error handling