-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement Delegate Property Validation with Generics
- Loading branch information
1 parent
bcbaa35
commit d51af79
Showing
3 changed files
with
30 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
28 changes: 28 additions & 0 deletions
28
krate/src/main/kotlin/hu/autsoft/krate/validated/ValidatedPreferenceDelegate.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
} | ||
|
||
} |
22 changes: 0 additions & 22 deletions
22
krate/src/main/kotlin/hu/autsoft/krate/validated/optional/ValidatedStringDelegate.kt
This file was deleted.
Oops, something went wrong.