Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning a string into a sealed trait using scala chimney

Tags:

scala

sealed trait Mode
object Mode {
  case object On extends Mode
  case object Off extends Mode
}

import io.scalaland.chimney.dsl._
"On".into[Mode].?????

I've tried using withCoproductInstance but i am not finding the right path

like image 718
TheDude Avatar asked Mar 03 '23 15:03

TheDude


1 Answers

What you do is not a type-based, automatic transformation between 2 data models that are ADTs (case class or sealed), java beans, etc or collections of such, generated safely in compile-time

It is a String parsing. (Done on runtime, so it can possibly fail). If you are parsing enums' names into enum's values often, I suggest using enumeratum (it supports many other operations on enums as well)

import enumeratum._

sealed trait Mode extends EnumEntry

object Mode extends Enum[Mode] {
  val values = findValues

  case object On  extends Mode
  case object Off extends Mode
}

Mode.withName("On")

This is simply not Chimney use case - and I say it as one of Chimney's co-authors.

Alternatively, if you don't want to modify your existing code, you can derive a type class for handling all kinds of enums implementations using enumz (disclaimer, I wrote the thing)

io.scalaland.enumz.Enum

Enum[Mode].withName("On")
like image 140
Mateusz Kubuszok Avatar answered Mar 05 '23 04:03

Mateusz Kubuszok