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

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.

主站蜘蛛池模板: 博罗县| 九江县| 洞头县| 新龙县| 广宗县| 开原市| 北票市| 罗平县| 西宁市| 昌宁县| 永寿县| 钟祥市| 临邑县| 乡宁县| 堆龙德庆县| 治多县| 上思县| 胶南市| 河间市| 沙洋县| 台东市| 咸丰县| 朝阳县| 南充市| 明水县| 白朗县| 佳木斯市| 常德市| 石渠县| 永川市| 睢宁县| 海丰县| 沙湾县| 台北县| 武安市| 翼城县| 专栏| 句容市| 霍林郭勒市| 宿迁市| 阿坝|