当前位置:网站首页>Scala method and function notes
Scala method and function notes
2022-06-13 03:28:00 【TRX1024】
Scala There are methods and functions , The semantic difference between them is very small .Scala Method is part of the class , and Function is an object , It can be assigned to a variable . In other words, a function defined in a class is a method .Scala The function in is a complete object ,Scala The functions in are actually inherited Trait Object of class .
Scala Use in val Statements can define functions ,def Statement definition method .
Be careful : Some translation functions (function) With the method (method) There is no difference .
1、Scala Method / Function definition
object Test {
def main(args: Array[String]): Unit = {
fun(10, 20)
println(sum(10, 20))
println(sum2(30, 20))
}
def fun(a: Int, b: Int) = {
println("a=" + a)
println("b=" + b)
}
def sum(a: Int, b: Int) = a + b
def sum2(a: Int, b: Int): Int ={
return a + b
}
}
Method is defined by a def Keyword start , This is followed by a list of optional parameters , A colon : And the return type of the method , An equal sign = , Finally, the main body of the method .
If the method does not return a value , The return type is Unit, Be similar to Java Medium void. Methods can write return value types , Or not , Automatically infer . Sometimes it cannot be omitted , For example Recursive function in 、 The return type of the function is Function type when , Write in method return Isochronous .
Scala When there is a return value in , Can write return, Or not , The function returns the last line as a result .
The method body can be timed in one line , Don't write { } .
Scala Specifies that the parameters passed to the method are
Constant val
Of , No var Of .
2、Scala Function name call (call-by-name)
Scala The interpreter parses function parameters (function arguments) There are two ways :
- Value transfer call (call-by-value): First calculate the value of the parameter expression , And then apply it to the inside of the function ;
- Call by name (call-by-name): Apply the non evaluated parameter expression directly inside the function
object SayHello {
def main(args: Array[String]): Unit = {
println(" Value transfer call :")
delayed0(time())
println("===================")
println(" Call by name :")
delayed(time())
println("===================")
}
def time() = {
println(" Acquisition time , It's in nanoseconds ")
System.nanoTime
}
def delayed0(t : Long)={
println(" stay delayed0 In the way ")
println(" Parameters "+t)
t
}
def delayed(t: => Long) = {
println(" stay delayed In the way ")
println(" Parameters : " + t)
t
}
}
We declared that delayed Method , This method is used in variable names and variable types => Symbol to set the name call ; Output results :
Value transfer call :
Acquisition time , It's in nanoseconds
stay delayed0 In the way
Parameters 232873973675933
===================
Call by name :
stay delayed In the way
Acquisition time , It's in nanoseconds
Parameters : 232873984381351
Acquisition time , It's in nanoseconds
===================
in short , The value passing call will calculate the value of the parameter before calling the method , The named call is after the method call , Call... Where parameters are used inside a method .
3、Scala Closure
Closure is a function , The return value depends on one or more variables declared outside the function .
Generally speaking, a closure can be simply regarded as another function that can access local variables in a function .
We introduce a free variable factor, This variable is defined outside the function .
Function variables defined in this way multiplier Become a " Closure ", Because it refers to variables defined outside the function , The process of defining this function is to capture this free variable to form a closed function .
example :
object Test {
def main(args: Array[String]) {
var factor = 3
val multiplier = (i:Int) => i * factor
println( "muliplier(1) value = " + multiplier(1) )
println( "muliplier(2) value = " + multiplier(2) )
}
}
Properties of closures
- 1. Function nested function
- 2. Functions can reference external parameters and variables internally
- 3. Parameters and variables are not recycled by the garbage collection mechanism
Common ways to create closures The function is created in the function
- 1. How to set private variables
- 2. Unsuitable scene : Functions that return closures are very large functions
- 3. Disadvantages resident memory , Will increase memory usage , Improper use causes memory leakage
Why use closures
- 1. To get local variables inside a function
- 2. A local variable inside a function that can only be read by a child function inside the function
- 3. Closures are bridges between the internal and external links of functions
Use of closures
- You can read the internal variables of the function , You can always keep the value of a variable in memory
4、 Recursive function
Must develop a The return type of the function
def fun(num :Int) :Int= {
if(num ==1)
num
else
num * fun2(num-1)
}
print(fun(4))
5、Scala function - Default parameter value
object Test {
def main(args: Array[String]) {
println( " Return value : " + addInt() );
}
def addInt( a:Int=5, b:Int=7 ) : Int = {
var sum:Int = 0
sum = a + b
return sum
}
}
6、Scala function - Variable parameters
Scala Set the variable parameter by placing an asterisk after the type of parameter ( Repeatable parameters ).
object Test {
def main(args: Array[String]) {
printStrings("I", "Love", "Scala");
}
def printStrings( args:String* ) = {
var i : Int = 0;
for( arg <- args ){
println("Arg value[" + i + "] = " + arg );
i = i + 1;
}
}
}
7、Scala function - Anonymous functions
Scala The syntax for defining anonymous functions in is simple , To the left of the arrow is a list of parameters , On the right is the function body .
def main(args: Array[String]): Unit = {
value1()
value2(2)
println(value3(3,4))
println(value4(4,5))
}
// Nonparametric anonymous function
val value1 = () => {
println("Hello word")
}
// Anonymous functions with parameters
val value2 = (a: Int) => {
println(a)
}
// Multiple parameters There is a return
val value3 = (a: Int, b: Int) => {
a * b
}
val value4 = (a: Int, b: Int) => a * b
8、Scala Higher order function
Higher order function (Higher-Order Function) Is a function that operates on other functions .
Scala Higher order functions are allowed in , Higher order functions can use other functions as parameters , Or use functions as output .
In the following example ,apply() Function uses another function f and value v As a parameter , The function f The parameter... Is called again v:
object Test {
def main(args: Array[String]) {
println( apply( layout, 10) )
}
// function f and value v As a parameter , The function f The parameter... Is called again v
def apply(f: Int => String, v: Int) = f(v)
def layout[A](x: A) = "[" + x.toString() + "]"
}
apply() in f Use =>String, Indicates that a function is called by name , The passed in function will be called at the position used by the function body .
边栏推荐
- Age anxiety? How to view the 35 year old programmer career crisis?
- DDL operation table
- Use of jstack
- [azure data platform] ETL tool (8) - ADF dataset and link service
- Cross border M & a database: SDC cross border database, Thomson database, A-share listed company M & a database and other multi index data (4w+)
- Large attachment fragment upload and breakpoint continuation
- [azure data platform] ETL tool (4) - azure data factory debug pipeline
- C method parameter: out
- Brief introduction: distributed cap theory and base theory
- Union, intersection and difference sets of different MySQL databases
猜你喜欢
Masa auth - SSO and identity design
The most complete ongdb and neo4j resource portal in history
Loading process of [JVM series 3] classes
Panel for measuring innovation efficiency of 31 provinces in China (using Malmquist method)
To resolve project conflicts, first-class project managers do so
Reading notes of effective managers
Technology blog, a treasure trove of experience sharing
Quickly obtain the attributes of the sub graph root node
Prefecture level city - air flow coefficient data - updated to 2019 (including 10m wind speed, boundary height, etc.)
Azure SQL db/dw series (10) -- re understanding the query store (3) -- configuring the query store
随机推荐
Video playback has repeatedly broken 1000w+, how to use the second dimension to create a popular model in Kwai
C # simple understanding - method overloading and rewriting
Add Yum source to install php74
Implode and explode in golang
Complex network analysis capability based on graph database
Level II C test skills
Microservice practice based on rustlang
MySQL create user authorization remote access
MySQL learning summary Xi: detailed explanation of the use of stored procedures and stored functions
Data of all bank outlets in 356 cities nationwide (as of February 13, 2022)
MySQL learning summary 6: data type, integer, floating point number, fixed-point number, text string, binary string
2016. maximum difference between incremental elements
Neil eifrem, CEO of neo4j, interprets the chart data platform and leads the development of database in the next decade
Simulink代码生成: 简单状态机及其代码
产品需求文档如何编写
[azure data platform] ETL tool (1) -- Introduction to azure data factory
[azure data platform] ETL tool (7) - detailed explanation of ADF copy data
Azure SQL db/dw series (13) -- using query store (2) -- report Introduction (2)
MySQL learning summary XIII: detailed explanation of if, case, loop, while & cursor of process control
C语言程序设计——从键盘任意输入一个字符串(可以包含:字母、数字、标点符号,以及空格字符),计算其实际字符个数并打印输出,即不使用字符串处理函数strlen()编程,但能实现strlen()的功能。