Article Directory
Definitions 1. Method
grammar
def methodName (参数名:参数类型, 参数名:参数类型) : [return type] = {
// 方法体:一系列的代码
}
Note item
- Parameter Type list can not be omitted
- Return type can be omitted, the compiler automatically inferred by the scala
- The return value can not write return, that is, the default value of the expression {} block
The sample code
//定义一个方法,实现两个整形数值相加,返回相加后的结果
//方式一
def add(a:Int,b:Int) : Int = {a + b}
//省略返回值的写法
def add(a:Int,b:Int)= {a + b}
//其它写法
def add(a:Int,b:Int) = a + b
//调用
add(1,2)
note
When defining the recursive method, the return type can not be omitted
The sample code
//定义递归方法(求阶乘)
//没有返回值写法 报错
def m2(x:Int) = {
if(x<=1) 1
else m2(x-1) * x
}
//有返回值写法,方法定义正确
def m2(x:Int):Int = { | if(x<=1) 1 | else m2(x-1) * x | }
2. The method parameters
Types of
- The default parameters
- With name parameter
- Vararg
The default parameters
When defining the method can define a default value for parameter.
The sample code
// x,y的默认值为0
//定义方法求两个数相加的值, 并且参数的的默认值为0
def add(x:Int = 0, y:Int = 0) = x + y
//调用
add();
With name parameter
When calling the method, you can specify the name of the parameter to make the call.
The sample code
def add(x:Int = 0, y:Int = 0) = x + y
add(x=1)
Vararg
If the parameters of the method is not fixed, a method may define the parameters is variable length parameter.
Syntax
//在参数类型后面加一个`*`号,表示参数可以是0个或者多个
def 方法名(参数名:参数类型*):返回值类型 = {
方法体
}
The sample code
//1. 定义一个计算若干个值相加的方法
//2. 调用方法,传入以下数据:1,2,3,4,5
// sum 求和
def add(num:Int*) = num.sum
//调用
add(1,2,3,4,5)
3. The method of calling
Called
- Suffix call law
- Infix call law
- France braces call
- Call the method without brackets
Suffix call law
Syntax
对象名.方法名(参数)
The sample code
Math.abs(-1)
Infix call law
grammar
对象名 方法名 参数
Note: The 如果有多个参数,使用括号括起来
code examples
Math abs -1
Method operator i.e.
The sample code
1 + 1
Explanation
In the scala, + - * /% of these operators and the like Java, but in the scala
all operators are methods
operator is a symbolic name of the method is a method
France braces call
Syntax
Note:方法只有一个参数,才能使用花括号调用法
Math.abs{
// 表达式1
// 表达式2
}
The sample code
Math.abs{-10}
Call the method without brackets
If the method has no parameters, names in brackets behind the method you can omit
the code sample
def m3()=println("hello")
m3