-
|
Hey all! I am new to pkl and modern languages in general, so this might be a stupid question for the people in the know. I have a complex class (deep with boolean, strings, floats and ints), and I want to compare two class instances to check that the configured class is equal for all strings, bool and equal or less than for all ints, floats. Is there a way to do this comparison? Perhaps piecemeal, a smart loop through all properties to check the values? A simple example: class Zone {
map: Boolean = false
limit: Float (isBetween(0, 120.0)) = 0.0
region: String
}
zone1 : Zone = new {
limit = 10.0
region = "south"
}
zone2 : Zone = new {
limit = 9.0
region = "south"
}
comparison1 = zone1 EqualOrGreaterThan zone2Is there a way to construct this "EqualOrGreaterThan" without the knowledge of the structure of the class? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
What determines if If you have a precise definition, you can define method for it: class Zone {
map: Boolean = false
limit: Float (isBetween(0, 120.0)) = 0.0
region: String
function isLessThan(other: Zone): Boolean =
limit < other.limit
|| region < other.region
}Sample usage: zones: List<Zone> = List(zone1, zone2)
result = zones.sortWith((z1, z2) -> z1.isLessThan(z2))Here's another version of a comparator that compares arbitrary classes by iterating through their properties and comparing property values that are hidden genericCompare: (Typed, Typed) -> Boolean = (value1, value2) ->
if (value1.getClass() != value2.getClass()) false
else
let (m1 = value1.toMap())
let (m2 = value2.toMap())
m1.fold(false, (comparison, key, value) ->
if (comparison == true) comparison
else
let (other = m2[key])
if (value is Comparable) value < other
else if (value is Typed) genericCompare.apply(value, other)
else false
)If this isn't exactly what you want, you'll need to tweak this to describe the logic you're looking for. And usage: result = zones.sortWith(genericCompare) |
Beta Was this translation helpful? Give feedback.
This doesn't quite seem right (if
value > other,comparisonends up beingfalseand thefoldcontinues). I'd makecomparisonnullable to distinguish between not-yet-decided and decided-false.Be m…