From 7158fccf2f6405e1b0ce480aa3870196a79b5def Mon Sep 17 00:00:00 2001 From: Albert Latacz Date: Wed, 3 Jan 2024 11:04:43 +0000 Subject: [PATCH] object field --- .../kotlin/dev/forkhandles/lens/MapWrapper.kt | 16 ++++++++++++---- .../dev/forkhandles/lens/MapWrapperTest.kt | 8 ++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/lens4k/src/main/kotlin/dev/forkhandles/lens/MapWrapper.kt b/lens4k/src/main/kotlin/dev/forkhandles/lens/MapWrapper.kt index bb47c64..f8b986e 100644 --- a/lens4k/src/main/kotlin/dev/forkhandles/lens/MapWrapper.kt +++ b/lens4k/src/main/kotlin/dev/forkhandles/lens/MapWrapper.kt @@ -1,9 +1,17 @@ package dev.forkhandles.lens +@Suppress("UNCHECKED_CAST") abstract class MapWrapper(private val map: Map) { class Field : AbstractLensProp({ map.containsKey(it) }, { map[it] }) - class ListField(mapFn: (IN) -> OUT) : AbstractLensProp>({ map.containsKey(it) }, { - @Suppress("UNCHECKED_CAST") - (map[it] as List).map(mapFn) - }) + class ListField(mapFn: (IN) -> OUT) : AbstractLensProp>( + { map.containsKey(it) }, + { (map[it] as List).map(mapFn) } + ) + + class ObjectField(wrapper: (Map) -> OUT) : + AbstractLensProp( + { map.containsKey(it) }, + { wrapper(map[it] as Map) } + ) + } diff --git a/lens4k/src/test/kotlin/dev/forkhandles/lens/MapWrapperTest.kt b/lens4k/src/test/kotlin/dev/forkhandles/lens/MapWrapperTest.kt index 890e2ae..dbc400b 100644 --- a/lens4k/src/test/kotlin/dev/forkhandles/lens/MapWrapperTest.kt +++ b/lens4k/src/test/kotlin/dev/forkhandles/lens/MapWrapperTest.kt @@ -21,6 +21,8 @@ class MapWrapperTest { val notAStringField by Field() val noSuchField by Field() val listField by ListField(::SubMap) + val listField2 by ListField(Any::toString) + val objectField by ObjectField(::SubMap) } @Test @@ -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" ) ) ) @@ -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 { mapBacked.notAStringField }.message.isEqualTo("Value for field is not a class kotlin.String but class kotlin.Int") expectThrows { mapBacked.noSuchField }.message.isEqualTo("Field is missing") }