当前位置:网站首页>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 valOf , 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 * b8、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 .
边栏推荐
- Technical documentbookmark
- Age anxiety? How to view the 35 year old programmer career crisis?
- PostgreSQL common SQL
- [synchronization function] version 2.0.16-19 has the update of synchronization function repair, but the problem has not been solved
- A data modeling optimization solution for graph data super nodes
- Masa auth - overall design from the user's perspective
- Brief introduction: distributed cap theory and base theory
- Personal understanding of grammar sugar
- Masa Auth - SSO and Identity Design
- Aggregation analysis of research word association based on graph data
猜你喜欢

brew工具-“fatal: Could not resolve HEAD to a revision”错误解决

Carbon neutralization & Patent Innovation: multi indicator data such as patent panels (original documents) of provinces, cities and counties, and the number of low-carbon patents authorized

Coal industry database - coal price, consumption, power generation & Provincial Civil and industrial power consumption data
![[azure data platform] ETL tool (2) -- azure data factory](/img/31/3561a3c3f24bce098330218a1d9ded.jpg)
[azure data platform] ETL tool (2) -- azure data factory "copy data" tool (cloud copy)

Feign based remote service invocation
![[azure data platform] ETL tool (3) - azure data factory copy from local data source to azure](/img/c3/e4b118a378ce8d884163aa1709a7f5.jpg)
[azure data platform] ETL tool (3) - azure data factory copy from local data source to azure

2000-2019 enterprise registration data of all provinces, cities and counties in China (including longitude and latitude, registration number and other multi indicator information)

Azure SQL db/dw series (14) -- using query store (3) -- common scenarios
![[JVM series 4] common JVM commands](/img/32/339bf8a2679ca37a285f345ab50f00.jpg)
[JVM series 4] common JVM commands
![[azure data platform] ETL tool (8) - ADF dataset and link service](/img/bf/d6d3a8c1139bb8d38ab9ee1ab9754e.jpg)
[azure data platform] ETL tool (8) - ADF dataset and link service
随机推荐
Isolation level, unreal read, gap lock, next key lock
C # simple understanding - static members and static classes
[JVM series 8] overview of JVM knowledge points
Feign based remote service invocation
MySQL and PostgreSQL installation subtotal
Azure SQL db/dw series (12) -- using query store (1) -- report Introduction (1)
Data from the first to seventh census (to counties)
C method parameter: params
PHP uses the header function to download files
Prefecture level city - air flow coefficient data - updated to 2019 (including 10m wind speed, boundary height, etc.)
Transaction processing in PDO
Three ways to start WPF project
C simple understanding - arrays and sets
Brief introduction: distributed cap theory and base theory
Implode and explode in golang
[JVM Series 2] runtime data area
Simulink代码生成: 简单状态机及其代码
C simple understanding - generics
MySQL learning summary Xi: detailed explanation of the use of stored procedures and stored functions
Solution of Kitti data set unable to download