Skip to content

Commit

Permalink
added optional support
Browse files Browse the repository at this point in the history
  • Loading branch information
daviddenton committed Jan 4, 2024
1 parent 07d19e2 commit c6affb0
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 3 deletions.
4 changes: 2 additions & 2 deletions data4k/src/main/kotlin/dev/forkhandles/data/DataContainer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ abstract class DataContainer<CONTENT>(
(get(it) as OUT)?.let(mapFn)
}

fun <IN : Any, OUT : Value<IN>> field(factory: ValueFactory<OUT, IN>) = field(factory::of)
fun <IN : Any, OUT : Value<IN>, OUT2 : OUT?> field(factory: ValueFactory<OUT, IN>) = field(factory::of)

fun <IN, OUT> list(mapFn: (IN) -> OUT) =
DataProperty<DataContainer<CONTENT>, List<OUT>>(exists) { get(it)?.let { (it as List<IN>).map(mapFn) } }
Expand All @@ -31,7 +31,7 @@ abstract class DataContainer<CONTENT>(

fun <OUT> list() = list<OUT, OUT> { it }

fun <OUT : DataContainer<CONTENT>> obj(mapFn: (CONTENT) -> OUT) =
fun <OUT : DataContainer<CONTENT>?> obj(mapFn: (CONTENT) -> OUT) =
DataProperty<DataContainer<CONTENT>, OUT>(exists) { (get(it) as CONTENT)?.let(mapFn) }

fun obj() = DataProperty<DataContainer<CONTENT>, CONTENT>(exists) { get(it) as CONTENT? }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ abstract class DataContainerContract {
expectThat(input.decimalField).isEqualTo(1.1234)

expectThat(input.mappedField).isEqualTo(123)
expectThrows<ClassCastException> { container(mapOf("mappedField" to 123)).mappedField }
expectThat(input.valueField).isEqualTo(MyType.of(123))

expectThat(input.optionalField).isEqualTo("optional")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class MapDataContainerTest : DataContainerContract() {

override val optionalField by field<String?>()
override val optionalListField: List<String>? by list()
override val optionalObjectField: SubClassFields? by obj(::SubMap)
override val optionalObjectField: SubMap? by obj(::SubMap)
override val optionalValueField: MyType? by field(MyType)
}

Expand Down

0 comments on commit c6affb0

Please sign in to comment.