Skip to content

Commit

Permalink
Implement Delegate Property Validation with Generics
Browse files Browse the repository at this point in the history
  • Loading branch information
kevincianfarini committed May 12, 2019
1 parent bcbaa35 commit 3c3d6d5
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 25 deletions.
4 changes: 2 additions & 2 deletions krate/src/main/kotlin/hu/autsoft/krate/Functions.kt
Expand Up @@ -14,7 +14,7 @@ import hu.autsoft.krate.optional.IntDelegate
import hu.autsoft.krate.optional.LongDelegate
import hu.autsoft.krate.optional.StringDelegate
import hu.autsoft.krate.optional.StringSetDelegate
import hu.autsoft.krate.validated.optional.ValidatedStringDelegate
import hu.autsoft.krate.validated.ValidatedPreferenceDelegate
import kotlin.properties.ReadWriteProperty

/**
Expand Down Expand Up @@ -65,7 +65,7 @@ public fun Krate.stringPref(key: String): ReadWriteProperty<Krate, String?> {
* @return [ReadWriteProperty]
*/
public fun Krate.stringPref(key: String, isValid: (String?) -> Boolean): ReadWriteProperty<Krate, String?> {
return ValidatedStringDelegate(StringDelegate(key), isValid)
return ValidatedPreferenceDelegate(StringDelegate(key), isValid)
}

/**
Expand Down
@@ -1,7 +1,6 @@
package hu.autsoft.krate.optional

import hu.autsoft.krate.Krate
import hu.autsoft.krate.validated.exception.KrateValidationException
import hu.autsoft.krate.util.edit
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
Expand Down
@@ -0,0 +1,28 @@
package hu.autsoft.krate.validated

import hu.autsoft.krate.Krate
import hu.autsoft.krate.validated.exception.KrateValidationException
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
* [ValidatedPreferenceDelegate] is a generic [ReadWriteProperty] that can be used to
* validate values that are being set.
*
* @param [delegate] the [ReadWriteProperty] implementation that is used for delegation
* @param [isValid] the lambda used to validate property values on [setValue]
*/
internal class ValidatedPreferenceDelegate<T>(
private val delegate: ReadWriteProperty<Krate, T>,
private val isValid: (T) -> Boolean
) : ReadWriteProperty<Krate, T> by delegate {

override operator fun setValue(thisRef: Krate, property: KProperty<*>, value: T) {
if (!isValid(value)) {
throw KrateValidationException("$value is not valid.")
}

delegate.setValue(thisRef, property, value)
}

}

This file was deleted.

0 comments on commit 3c3d6d5

Please sign in to comment.