代码之家  ›  专栏  ›  技术社区  ›  scout

不带参数的函数,在scala中以unit作为参数

  •  31
  • scout  · 技术社区  · 16 年前
     def foo(x:Int, f:Unit=>Int) = println(f())
    
    foo(2, {Unit => 3+4}
    
    //case1
    def loop:Int = 7
    foo(2, loop) //does not compile
    
    changing loop to 
    //case 2
    def loop():Int = 7
    foo(2, loop) // does not compile
    
    changing loop to
    //case 3
    def loop(x:Unit): Int = 7 //changing according to Don's Comments
    foo(2,loop) // compiles and works fine
    

    案例1和案例2也应该有效吗?他们为什么不工作?

    将foo定义为

    def foo(x:Int, y:()=>Int)
    

    那么情况2起作用,但情况1不起作用。

    它们不是都应该工作的吗,以任何一种方式定义函数。

    //我也认为()=>int在foo中是一个糟糕的样式,y:=>int不工作,注释??

    3 回复  |  直到 16 年前
        1
  •  80
  •   Rex Kerr    16 年前

    scala区分了以下几点:

    • 功能/方法 无参数列表 (“按名称参数”如果是函数)
    • 功能 一个空参数列表
    • 功能 一个单元型参数

    尽管scala允许您省略空参数列表,但这些都不是等价的。(顺便说一下,两个空参数列表也不相同。)

    所以,尽管 Unit 是书面的 () ,这是 不 与函数参数parens相同 () 用于函数或方法。相反,想想 () 作为一个 Tuple0 .

    所以,如果你说 f: Unit => Int ,您的意思是“f接受一个参数,但它是一个非常无聊的参数,因为它是 单位 ,一定总是一样无聊 tup0 价值 () “。你写的东西真的很短 f: (Unit) => Int .

    如果你说 f: () => Int ,那么您的意思是“f不接受任何参数并生成 Int “。

    如果你说 f: => Int ,那么您的意思是“延迟执行生成 int 值,直到我们在此代码中使用它(并每次重新计算它)。从功能上来说,这和 F:()=>整数 (内部转换为 Function0 但是它有一个不同的用法,大概是为了允许更紧凑的闭包形式(您总是忽略 => 在调用代码中)。

        2
  •  14
  •   Eastsun    16 年前

    ()=>int是function0[int],unit=>int是function1[unit,int]

    scala> val function0: () => Int = () => 5
    function0: () => Int = <function0>
    
    scala> val function1: Unit => Int = u => 5
    function1: (Unit) => Int = <function1>
    
    scala> function0()
    res0: Int = 5
    
    scala> function1("anything")
    res1: Int = 5
    
    scala> function1(100)
    res2: Int = 5
    
    scala>
    

    还要注意()是unit的对象

    scala> function1(())
    res11: Int = 5
    
    scala> function1 ()
    res12: Int = 5
    
    scala> function1()
    res13: Int = 5
    
    scala> val unit = ()
    unit: Unit = ()
    
    
    scala> function1(unit)
    res15: Int = 5
    
    scala> function1 apply unit
    res16: Int = 5
    
    scala>
    
        3
  •  2
  •   Don Mackenzie    16 年前

    在上述情况1和2中,返回值 环 而不是 环 对第二个参数的 福 失败了: 英特!=单位=>整数

    更改为 环 有打字错误。

    推荐文章