scala-Basics: The difference between method and function

Simple explanation

Method (method)
in OOP, the method acts on the object, it is the behavior of the object, the method in Java is the same, the method in Scala (method) is also the same, define the basic format of the method:
def method name (parameter list): Return value = method body

Function (function)
in scala, function is regarded as a first-class citizen, define the basic format of the function:
val f1 = (x: Int) => println (x) // print
val f2 = (x1: Int) => x1 + 4 // + 4 original data

Some examples

scala> def add3(x:Int) = x + 3
add3: (x: Int)Int // 表示Method add3有一个参数Int型参数x,返回值是Int型.

scala> add3(3)
res0: Int = 6

scala> val f1 = (x:Int) => x + 3
f1: Int => Int = <function1> // 表示Function f1的method体接受一个Int型的参数,输出结果的类型是Int型。f1的类型是function1

scala> f1(3)
res1: Int = 6

the difference

  • The parameter list is optional for method and is required for function (function parameter list can be empty)
scala> def method = println("没有参数的方法")
method: Unit

scala> val function = () => println("没有参数的函数") // f2: () => Unit = <function0>
scala> val function = => println("没有参数的函数") // 编译错误,参数列表可以为空,但不能省略
  • Method name means Method call, Function name just represents Function itself
scala> method
没有参数的方法

scala> function
res10: () => Unit = <function0>
  • A method can be provided where the function is needed (it will be automatically converted into a function, and this behavior is called ETA expansion)
// 高阶函数foreach接收的是一个函数,但也可以传入一个方法,scala会将这个方法自动转义成函数。
// foreach是List对象的一个高阶函数,它接收一个函数,并应用于List中的每一个元素,而method是一个方法。
def method(x: Any) = println(x)
val list = List[String]("Scala", "Spark", "Java")
list.foreach(method(_))

Note:
Where Function is expected, we can use Method.
Where Function is not expected, Method is not automatically converted to Function.

Operators are interpreted as methods in scala:

Prefix operator: op obj is interpreted as obj.op
infix operator: obj1 op obj2 is interpreted as obj1.op (obj2)
suffix operator: obj op is interpreted as obj.op

You can add an underscore after the Method name to force it into a Function. Note: There is at least one space between the Method name and the underscore! !

scala> def method1(x:Int) = { x + 84 }
method1: (x: Int)Int

scala> val function1 = method1 _
function1: Int => Int = <function1>

scala> function1(3)
res5: Int = 87

scala>

Guess you like

Origin www.cnblogs.com/duchaoqun/p/d56aa807f7d592fc598bf8b5c7d8a8e6.html