I’m very new to programming in general and am trying to figure out how to add up some integers from specific objects. I have a class called Shapes
with various objects. Each object has a property about its shape (either square
or circle
) and a integer with its size.
What I’m trying to figure out is how to write a function to add up just the sizes from each shape with a square
. Is there a way to iterate through each object in the class to check for the shape and add the size to a variable if it matches? Thanks in advance.
You can do it either using a loop (imperative style), or using monadic/functional operations (declarative style) :
Imagine you’ve got such an input data:
enum ShapeType { square, circle, triangle }
data class Shape(val type: ShapeType, val size: Int)
val myShapes = listOf(Shape(ShapeType.square, 3),
Shape(ShapeType.circle, 2),
Shape(ShapeType.square, 4))
With imperative style, you prepare a sum
variable to accumulate size into, and then, iterate over each element in the list, and evaluate it to check if you should add its size to the sum
or not:
fun computeSum(shapes: Iterable<Shape>, targetType: ShapeType) : Int {
// Accumulator variable
var sum = 0
// Evaluation loop
for (shape in shapes) {
if (shape.type == targetType) {
// update only when current element meets our condition
sum += shape.size
}
}
return sum
}
Now, as an exercise, you could check how to use filter
, and sumOf
functions to do the same thing with declarative style.
1 Like
The Iterable interface is what I needed, thank you! I will also look into the extension functions after I’ve finished my project.
1 Like