scala 传值参数和传名参数 ():=>和:=>

传值参数代码示例:

def test1(code: ()=>Unit){
    println("start")
    code() //要想调用传入的代码块,必须写成code(),否则不会调用。  
    println("end")
  }
  test1 {//此代码块,传入后立即执行。  
    println("1111")
    ()=>{println("2222")}
  }
  输出内容:
  1111
  start
  2222
  end   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

传名参数的示例:

def test(code : => Unit){  
  println("start")  
  code // 这行才会调用传入的代码块,写成code()亦可  
  println("end")  
}  
test{// 此处的代码块不会马上被调用  
  println("1111")  
  println("2222")   
} 
输出结果:
  start
  1111  
  2222
  end
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

因为scala建议如果函数的参数只有一个,可以考虑使用{}代替(),因此test和test1的调用都是{},又因为test的参数是传名参数函数,因此传入的参数是不会被执行的,而test1的参数是传值参数,因此需要先计算参数的值,然后再传入test1的方法体中,恰好test1传入参数的计算结果是一个匿名函数,因此可以执行,如果test1的传入参数的计算结果不是函数,那么就会报错。所以test和test1的调用,输出结果有所不同。 
文章参考 : 
=>Unti和:=>的区别http://scalagroup.group.iteye.com/group/topic/26303, 当然本片文章的内容介绍的是:=>和():=>的区别。 

而=>Unit和:=>的区别是,() => Unit是一个函数,=> Unit 是一个执行结果为Unit的表达式。

如下是stackoverflow的回答

The example you have given only uses call-by-value, so I will give a new, simpler, example that shows the difference.

First, let's assume we have a function with a side-effect. This function prints something out and then returns an Int.

def something() = {
  println("calling something")
  1 // return value
}

Now we are going to define two function that accept Int arguments that are exactly the same except that one takes the argument in a call-by-value style (x: Int) and the other in a call-by-name style (x: => Int).

def callByValue(x: Int) = {
  println("x1=" + x)
  println("x2=" + x)
}

def callByName(x: => Int) = {
  println("x1=" + x)
  println("x2=" + x)
}

Now what happens when we call them with our side-effecting function?

scala> callByValue(something())
calling something
x1=1
x2=1

scala> callByName(something())
calling something
x1=1
calling something
x2=1

So you can see that in the call-by-value version, the side-effect of the passed-in function call (something()) only happened once. However, in the call-by-name version, the side-effect happened twice.

This is because call-by-value functions compute the passed-in expression's value before calling the function, thus the same value is accessed every time. However, call-by-name functions recomputethe passed-in expression's value every time it is accessed


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值