Skip to content

Commit 0136a80

Browse files
committed
added more methods
1 parent 935ed30 commit 0136a80

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

scala-core-modules/scala-core-numbers-2/src/main/scala/com/baeldung/scala/listsum/SumList.scala

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,8 @@ object SumList {
3333
rec(list, 0)
3434
}
3535

36+
def sumNumeric[T](list: List[T])(using numeric: Numeric[T]): T = {
37+
list.sum
38+
}
39+
3640
}

scala-core-modules/scala-core-numbers-2/src/test/scala/com/baeldung/scala/listsum/SumListUnitTest.scala

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class SumListUnitTest
2222
("sumByReduce()", SumList.sumByReduce),
2323
("sumByIteration()", SumList.sumByIteration),
2424
("sumByFor()", SumList.sumByFor),
25-
("sumByTailRecursion()", SumList.sumByTailRecursion),
25+
("sumByTailRecursion()", SumList.sumByTailRecursion)
2626
)
2727

2828
it should "calculate sum for a list" in {
@@ -35,4 +35,23 @@ class SumListUnitTest
3535
}
3636
}
3737

38+
it should "calculate sum for any numeric types" in {
39+
val ints = List(1, 2, 3, 4)
40+
SumList.sumNumeric(ints) shouldBe 10
41+
SumList.sumNumeric(List.empty[Int]) shouldBe 0
42+
43+
val doubles = List(1d, 2d, 3d, 4d)
44+
SumList.sumNumeric(doubles) shouldBe 10d
45+
46+
val bigints = List(BigInt(1), BigInt(2), BigInt(3), BigInt(4))
47+
SumList.sumNumeric(bigints) shouldBe BigInt(10)
48+
49+
}
50+
51+
it should "calculate the sum of inside fields" in {
52+
case class Item(price: Int)
53+
val items = List(Item(1), Item(2), Item(3), Item(4))
54+
items.foldLeft(0)((acc, item) => acc + item.price) shouldBe 10
55+
}
56+
3857
}

0 commit comments

Comments
 (0)