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

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.

主站蜘蛛池模板: 威远县| 习水县| 阳泉市| 贡觉县| 色达县| 福泉市| 芜湖市| 徐州市| 华容县| 绥江县| 承德县| 兰考县| 巧家县| 镇赉县| 项城市| 广宗县| 平和县| 比如县| 奉化市| 洪江市| 灵石县| 外汇| 大埔县| 三原县| 宁晋县| 长泰县| 湖南省| 阿合奇县| 遂宁市| 江达县| 西畴县| 绍兴市| 法库县| 扶绥县| 黄骅市| 丰台区| 曲靖市| 定结县| 沙田区| 肇东市| 渭南市|