Skip to content

Commit

Permalink
object field
Browse files Browse the repository at this point in the history
  • Loading branch information
albertlatacz committed Jan 3, 2024
1 parent 77b39bd commit 7158fcc
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
16 changes: 12 additions & 4 deletions lens4k/src/main/kotlin/dev/forkhandles/lens/MapWrapper.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
package dev.forkhandles.lens

@Suppress("UNCHECKED_CAST")
abstract class MapWrapper(private val map: Map<String, Any?>) {
class Field<OUT> : AbstractLensProp<MapWrapper, OUT>({ map.containsKey(it) }, { map[it] })
class ListField<IN, OUT>(mapFn: (IN) -> OUT) : AbstractLensProp<MapWrapper, List<OUT>>({ map.containsKey(it) }, {
@Suppress("UNCHECKED_CAST")
(map[it] as List<IN>).map(mapFn)
})
class ListField<IN : Any, OUT>(mapFn: (IN) -> OUT) : AbstractLensProp<MapWrapper, List<OUT>>(
{ map.containsKey(it) },
{ (map[it] as List<IN>).map(mapFn) }
)

class ObjectField<OUT : MapWrapper>(wrapper: (Map<String, Any?>) -> OUT) :
AbstractLensProp<MapWrapper, OUT>(
{ map.containsKey(it) },
{ wrapper(map[it] as Map<String, Any?>) }
)

}
8 changes: 8 additions & 0 deletions lens4k/src/test/kotlin/dev/forkhandles/lens/MapWrapperTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ class MapWrapperTest {
val notAStringField by Field<String>()
val noSuchField by Field<String>()
val listField by ListField(::SubMap)
val listField2 by ListField(Any::toString)
val objectField by ObjectField(::SubMap)
}

@Test
Expand All @@ -36,6 +38,10 @@ class MapWrapperTest {
"listField" to listOf(
mapOf("stringField" to "string1"),
mapOf("stringField" to "string2"),
),
"listField2" to listOf("string1", "string2"),
"objectField" to mapOf(
"stringField" to "string"
)
)
)
Expand All @@ -46,6 +52,8 @@ class MapWrapperTest {
expectThat(mapBacked.longField).isEqualTo(Long.MAX_VALUE)
expectThat(mapBacked.decimalField).isEqualTo(1.1234)
expectThat(mapBacked.listField.map { it.stringField }).isEqualTo(listOf("string1", "string2"))
expectThat(mapBacked.listField2).isEqualTo(listOf("string1", "string2"))
expectThat(mapBacked.objectField.stringField).isEqualTo("string")
expectThrows<NoSuchElementException> { mapBacked.notAStringField }.message.isEqualTo("Value for field <notAStringField> is not a class kotlin.String but class kotlin.Int")
expectThrows<NoSuchElementException> { mapBacked.noSuchField }.message.isEqualTo("Field <noSuchField> is missing")
}
Expand Down

0 comments on commit 7158fcc

Please sign in to comment.