I’m trying to use Iso’s to retrain information bet...
# arrow
k
I’m trying to use Iso’s to retrain information between type conversions. I have an enum that has the type along with a property label that I need to use for data extraction. I then have it’s Iso for transforming the string representation to its type (and back again) for persistence. The problem I’m facing is that I can’t apply a type to the enum to retain the types of the Iso’s. I can take it from
String -> Any
and hope the compiler does what it does but I can go from
Any -> String
unless there is some unsafe compiler warning I can add to the code (which i want to avoid). What I have is:
Copy code
enum class Attribute(val label: String, val iso: Iso<String, *>) {
    FOO("foo:options", stringToInt),
    BAR("bar:values", intToList),
    BAZ("baz:id", stringToUuid),
}
Copy code
typealias NodeAttributes = Map<NodeAttribute, Any>
Copy code
ColumnAdapter<NodeAttributes, String> =
    object : ColumnAdapter<NodeAttributes, String> {
        override fun decode(databaseValue: String): NodeAttributes {
            val attributes = jacksonObjectMapper().readValue(databaseValue, object : TypeReference<NodeAttributes>() {})
            return attributes.mapValues { (key, value) -> 
                key.iso.get(value.toString()) // type mismatch required any found any?
            }
        }

        override fun encode(value: NodeAttributes): String {
            value.mapValues { (key, value) ->
                key.iso.reverseGet(value) // Type mismatch required nothing found any 
            }
            return jacksonObjectMapper().writeValueAsString(value)
        }
    }
Is there a better way to retain type information?
a
one way to handle this is to create a class which "remembers" the type it was instantiated with
Copy code
class Representation<A> private constructor(val representation: String) {
  override fun toString() = representation
}
then you can have something going in both directions
however, I would challenge this being a real
Iso<A, String>
, since you do not have a way to move from every string into an
A
, just for a subset of those. This is exactly where prisms can help you