官术网_书友最值得收藏!

  • Scala Programming Projects
  • Mikael Valot Nicolas Jorand
  • 270字
  • 2021-07-23 16:25:18

Implementing the Main method

Now that all our tests are green, we can implement the main method. The implementation becomes trivial as all the code is already in the test:

object Main extends App {
val persons = List(
Person(firstName = "Akira", lastName = "Sakura", age = 12),
Person(firstName = "Peter", lastName = "Müller", age = 34),
Person(firstName = "Nick", lastName = "Tagart", age = 52))

val adults = Person.filterAdult(persons)
val descriptions = adults.map(p => p.description).mkString("\n\t")
println(s"The adults are \n\t$descriptions")
}

The first thing is to define a list of Person, so that Person.filterAdult() is used to remove all the persons, not the adults. The adults variable is a list of Person, but I would like to transform this list of Person into a list of the description of the Person. To perform this operation, the map function of the collection is used. The map function transforms each element of the list by applying the function in the parameter.

The notation inside the map() function defines an anonymous function that takes p as the parameter. The body of the function is p.description. This notation is commonly used whenever a function takes another function as an argument.

Once we have a list of descriptions, we create a string with the mkString() function. It concatenates all the elements of the list using the special character \n\t, which are respectively the carriage return and the tab character.

Finally, we perform the side effect, which is the print on the console. To print in the console, the println alias is used. It is a syntactic sugar for System.out.println.

主站蜘蛛池模板: 尚义县| 奈曼旗| 岳西县| 芜湖市| 高台县| 上杭县| 丹凤县| 睢宁县| 临桂县| 平陆县| 宜兴市| 涟源市| 屯门区| 津南区| 吴桥县| 新巴尔虎左旗| 健康| 铁岭县| 科技| 沁水县| 旌德县| 余江县| 庆安县| 塔河县| 体育| 鲁甸县| 昭平县| 九寨沟县| 平昌县| 延吉市| 盐山县| 佛坪县| 宜州市| 北辰区| 无棣县| 米泉市| 临沂市| 台东市| 清丰县| 玉田县| 蒙阴县|