Hello!
I have released ‘kotlin-utils’ v0.7
What news:
-
Migrate to Kotlin v1.3.0
-
New extension for Collections.oneOrNull() - returns single value of collection or null
for collection with size not equals one (e.g. empty collection).
-
Property delegate for Comparable value (e.g. Int, Long) - PropertyRange.
This can be helpful when you want to keep you integer property in the specified range or e.g. only positive.
val number1: Int by PropertyRange(5, 3…7)
In this example 5 is initial value and 3…7 is valid range for property number1.
Also, you can choose behavior on range violation.
By default, if a new value less than minimal range value it silently changed to minimal and same rule for a maximum edge.
number1 = 10 // in fact will be 7
number1 = -100 // in fact will be 3
But you can write your own violation handler or pass second existing handler which throws IllegalArgumentException: exceptionViolation()
val number2: Int by PropertyRange(0, 0) // Only minimal edge set — zero, so this one only for positive values.
val number3: Long by PropertyRange(-7, max = 128) // Only maximum edge set — max value is 128.
- Property delegate to cache mutable value.
E.g. you have some mutable list and you want to have a property which contains the actual sum of the list:
val list = mutableListOf(1, 2, 3)
val sumOfList by CachedProperty(list) {
sum() // ‘this’ in this block is monitored object ie list.
}
On the first access, the code block with sum() will be called and the result of the operation will be stored in the property.
Also, hashCode of the list will be stored in the property.
On the second access, if the list was not changed ie hashCode is still equaled with stored in property just cached value will be returned. Ie code block with sum() will not be called.
In addition, you can implement your own logic of tracking an object without using of hashCode.
For immutable objects, you can use a hint for CachedProperty and it will be like lazy() delegate.
Example of a topological sort for the graph (see attached picture):
val analyst = analystOf(edge(“A”, “B”, 1),
edge(“A”, “C”, 2),
edge(“B”, “C”, 3),
edge(“B”, “D”, 4),
edge(“C”, “E”, 5),
edge(“E”, “D”, 6),
edge(“C”, “F”, 7),
edge(“F”, “E”, 8),
edge(“G”, “A”, 9),
edge(“G”, “F”, 10))
analyst.sortTopological()
Result is: “G”, “A”, “B”, “C”, “F”, “E”, "D"