Scala 返回一个带有 0 个参数的 void 函数,语法难看? [英] Scala Returning a void function with 0 parameters, ugly syntax?

查看:44
本文介绍了Scala 返回一个带有 0 个参数的 void 函数,语法难看?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个如下定义的方法

Given a method defined as follows

 def descendEach(times:Int)(f:()=>Unit) {
      for (i <- 1 to times) {
          // other code
          f()
      }
   }

当我使用这种方法时,我希望能够写

when I use this method I want to be able to write

 gd.descendEach(20){
    println(gd.cost)
 }

但Scala编译器只让我逃脱

but the scala compiler only lets me get away with

  gd.descendEach(20){ () => 
    println(gd.cost)
 }

有点丑.我在这里错过了什么吗?可以按照我介绍的第一种方式写吗?

which is kind of ugly. Am I missing something here? Is it possible to write it in the first way I presented?

推荐答案

使用以下语法:

def descendEach[T](times:Int)(f: => T)

这样你不仅可以在没有额外的() =>(这称为按名称传递)的情况下传递函数,而且还可以使用返回任何类型的函数(不是必须 Unit).当您有一个想要传递的现有函数但并不真正关心它的返回值时,有时会很方便:

This way you can not only pass function without extra () => (this is called pass by name), but also use functions returning any type (not necessarily Unit). It is sometimes convenient when you have an existing function you want to pass but don't really care about its return value:

def g() = 42
descendEach(20)(g)

请注意,使用此语法,您只需使用 f,而不是 f().

Note that with this syntax you are simply using f, not f().

这篇关于Scala 返回一个带有 0 个参数的 void 函数,语法难看?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆