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

Declaring and calling functions

A Scala function takes 0 to n parameters and returns a value. The type of each parameter must be declared. The type of the returned value is optional, as it is inferred by the Scala compiler when not specified. However, it is a good practice to always specify the return type, as it makes the code more readable:

scala> def presentation(name: String, age: Int): String = 
"Hello, my name is " + name + ". I am " + age + " years old."
presentation: (name: String, age: Int)String

scala> presentation(name = "Bob", age = 25)
res1: String = Hello, my name is Bob. I am 25 years old.

scala> presentation(age = 25, name = "Bob")

res2: String = Hello, my name is Bob. I am 25 years old.

We can call a function by passing arguments in the right order, but we can also name the arguments and pass them in any order. It is a good practice to name the arguments when some of them have the same type, or when a function takes many arguments. It avoids passing the wrong argument and improves readability.

主站蜘蛛池模板: 洱源县| 乌兰县| 宁强县| 邻水| 新晃| 福鼎市| 兴海县| 甘南县| 新郑市| 高青县| 白水县| 博客| 宽甸| 新竹市| 察哈| 德兴市| 南皮县| 东明县| 鲜城| 绥棱县| 平昌县| 南雄市| 深泽县| 陆河县| 文山县| 临朐县| 建湖县| 莲花县| 阳谷县| 广安市| 廉江市| 通山县| 随州市| 佛山市| 海南省| 嵩明县| 麻栗坡县| 新营市| 米泉市| 阿荣旗| 隆德县|