Practice typed Scala functions and transformations of immutable lists.
Before starting: Basic values and lists.
Practice project: Extend the examples into a small Scala study demo. Explain the setup, one normal case and one failure or boundary case.
Start here: concepts and guided practice
- Transform an immutable list in Scala
Scala combines functional and object-oriented programming. A val cannot be reassigned. List.map builds a new list by applying a function to each value; it does not change the original immutable list.
Scala 3; save as Scores.scala and run with a Scala 3 toolchain
@main def scores(): Unit = val values = List(4, 7, 2) val doubled = values.map(_ * 2) println(doubled.mkString(", "))Check the output
8, 14, 4Try an empty List[Int] and predict an empty printed line.
- Scala: filter an immutable list
filter returns a list of values for which the predicate is true. The original immutable list is not changed. A val prevents reassignment; immutability of the collection is a separate property.
Scala 3 toolchain; save as Study.scala and run with a Scala 3 runner.
@main def study(): Unit = val scores = List(0, 4, -2, 7) val kept = scores.filter(_ > 0) println(kept.mkString(", "))Check the output
4, 7Use >= 0 and predict the additional value.
- Scala: declare a typed function
A function can state its input and result types. The expression following = supplies its result. Keeping calculations separate from printing makes them easier to test.
Scala 3 toolchain; save as Study.scala and run with a Scala 3 runner.
def minutesFor(lessons: Int): Int = lessons * 15 @main def study(): Unit = println(minutesFor(3))Check the output
45Call minutesFor(0), then describe an appropriate check for negative counts.
Open the Scala learning path on DevStudyHub · Play coding games on this blog
No comments:
Post a Comment
Please do not enter any spam link in the comment box.