Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between a Scala method and a function

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you what is the difference between Scala methods and functions. The article is rich in content and analyzes and describes it from a professional point of view. I hope you can get something after reading this article.

There are both Function and Method in Scala, and in most cases we can ignore the differences between them. But sometimes we have to understand the differences between them.

The methods in Scala are the same as the methods in Java, and the methods are part of the constituent class. The method has a name, type signature, and sometimes comments on the method, as well as the functional implementation code (bytecode) of the method.

The function in Scala is a complete object. The concept of function is abstracted by 22 trait in Scala. These 22 traits range from Function1 to Function22:

For example, the Function10 in the figure above represents a function with 10 formal parameters and a return value of R (covariant).

Anonymous functions are more commonly used. You only need to specify the type and body of the input parameters when defining them. You don't need a name. If you use them, you will generally assign this anonymous function to a variable (actually a val constant).

Representation: (input parameters) = > {method body}

Val f = (name:String) = > println ("Hi," + name) f ("kafka")

The functions in Scala are actually objects that inherit these Trait classes, for example, we define a function by function numeric surface quantities.

In fact, the above function is defined in the same way as the following:

Because Function2 is a trait, it cannot be directly new. The above new Function2 [Int,Int,Int] () {} is actually an object that defines and instantiates a class that implements Function2 attributes.

Apply is the grammatical sugar in scala: when obj () is called on an object obj, the scala compiler converts to obj.apply (); when clazz () is called on a class clazz, the scala compiler converts to clazz_company_obj.apply (), where clazz_company_obj is the companion object of clazz.

The specific differences are summarized as follows:

1. A method cannot exist as a separate expression (except for a method with an empty parameter), and a function can. Such as:

Definition of scala > def m (x:Int) = 2.0*xm: (x:Int) Double method scala > val f = (x:Int) = > 2.0 functions f: Int = > Double = function definition scala > fres7: Int = > Double = function is scala > val tmp = m _ can also achieve method-to-function changes tmp: Int = > Double = scala > m calling the method name directly is wrong: 13: error: missing argument list For method mUnapplied methods are only converted to functions when a function type is expected.You can make this conversion explicit by writing `m _ `or `m (_) `instead of `m`. M ^ in Scala, a function is also an object, and each object is an instance of scala.FunctionN (1-22), where N is the number of function arguments. For example, we define a function and copy it to a variable: scala > val f = (x: Int) = > x + 1 (anonymous function) f: Int = > Int = A function that takes an integer variable as a parameter is defined here The function is to return input parameters plus 1. You can see that the toString method of the REPL return parameter is. So if we have a reference to a function object, how do we call this function? The answer is through FunctionN's apply method, that is, FunctionN.apply (), so the method to call the function object is as follows: scala > f.apply (3) res2: Int = 4, but if you call the method object through FunctionN.apply (x, y...), it will be a bit verbose. Scala provides a format to call the function object scala > f (3) res3: Int = 4.

In the example above, we first define a method m, followed by a function f. Then we use the function name (function value) as the final expression, which is completely correct because f itself is an object (an object that implements the FunctionN attribute). But if we use the method name as the final expression, we will make an error.

two。 A method can have no argument list and a function must have a parameter list

Scala > def M1 = 100m1: Int method definition without input parameters is the following abbreviated form: scala > def m2 () = 100m2: () Int without input parameters into the definition scala > val F1 = () > 100FunctionDefinitions without input parameters F1: () = > Int = scala > val F1 = > 100 imitating the top words, the error report is directly reported: 1: error: illegal start of simple expressionval F1 = > 100

In the example above, the M1 method accepts zero parameters, so the parameter list can be omitted. The function cannot omit the parameter list.

3. The method name is the method call, while the function name only represents the function object itself.

This is easier to understand. Because the variable that holds the surface quantity of a function (also known as a function name or function value) is itself an object of a class that implements FunctionN characteristics, to call the object's apply method, you need to use the syntax of obj (). So the function name is called by parentheses. As follows:

Scala > def M1 = 100m1: Int method definition scala > val F1 = () = > 100FunctionDefinitions F1: () = > Int = scala > M1 method call res11: Int = 100scala > F1 function View res12: () = > Int = scala > F1 () function call is the correct form of res13: Int = 100scala > f1.apply () function call.

4. Where a function is needed, if a method is passed, the ETA expansion will be performed automatically (convert the method to a function)

As above, an error will be reported if we assign a method directly to a variable. If we specify that the type of the variable is a function, it can be compiled as follows:

Scala > val F1: (Int) = > Int = mf1: Int = > Int =

Of course, we can also force a method to be converted to a function, which uses some of the application functions in scala:

Scala > val F1 = m _ F1: Int = > Int = scala > val F1 = m (_) F1: Int = > Int =

5. The naming parameter is essentially a method.

A filename parameter is essentially a method in which the argument list is empty, because the argument list of a function cannot be empty! (reference for difference 2), as follows:

Scala > def M1 (x: = > Int) = List (xMagol x) M1: (x: = > Int) List [Int]

As shown above, the code actually defines a method, M1, whose parameter is a name parameter (method). Because the method name is the method call for a method with empty parameters, List (x _ Magnex) actually makes two method calls.

Because List (XMagol x) makes two method calls, you get two different values. If we slightly modify the definition of M1 of the function and cache x first, the result will be very different.

Scala > def M1 (x: = > Int) = {val y = x political list (yscoy)} M1: (x: = > Int) list [int] scala > M1 (r.nextInt) res18: List [Int] = List (- 723271792,-723271792)

6. Method and function as parameter call

/ method definition def method1 (arge1: Int, arge2: Int) = arge1 + arge2 / / function definition val funct1 = (arge1: Int, arge2: Int) = > arge1-arge2 def method2 (f: (Int, Int) = > Int) = f (12,12) println ("method passing method" + method2 (method1)) val funct2 = (f: (Int, Int) = > Int) = > f (22) 22) println ("function transfer method" + funct2 (method1)) def method3 (f: (Int, Int) = > Int) = f (4,1) println ("method transfer function" + method3 (funct1)) val funct3 = (f: (Int, Int) = > Int) = > f (5) 1) println ("function transfer function" + funct3 (funct1))-/ / call method call Method def method1 (): Unit = println ("printmethod1") def method2 (m: () = > Unit): Unit = m () / / if the parameter list is called with (), it should also be called with () method2 (method1) / / execute / / call method def method11: Unit = println ("printmethod11") def method22 (m: = > Unit) = m / / such as If there is no () in the parameter list, m () method22 (method11) / / execution / / call mode 3 def method111 (): Unit = println ("printmethod111") def method222 (m: () = > Unit) = m / / if the parameter list is called with () without () Then method222 (method111) / / there is no output here

Apply explanation in Scala

Class ApplyTest {def apply () = println ("I am into Spark so muchboxes!") Def haveATry {println ("Have a try on apply!")} object ApplyTest {def apply () = {println ("I am into Scala so muchboxes!") New ApplyTest}} object ApplyOperation {def main (args: Array [String]) {val array = Array val a = ApplyTest () / / there is no new here, and then it does return an instance of the class a.haveATry}}

Output result:

I am into Scala so much!!!Have a try on apply!

In the accompanying object of a class, implement the apply method, where you can create an instance of the class. For example, val a = Array (1, 2, 3) uses Array's apply method.

Similarly, you can use the apply method in class:

Object ApplyOperation {def main (args: Array [String]) {val a = new ApplyTest a.haveATry println (a ()) / / call the apply method of class}}

Results:

Have a try on applyboards I am into Spark so muchboxes! () these are the differences between Scala methods and functions shared by the editor. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report