显式类型的call-by-name函数参数

时间:2014-05-23 00:02:06

标签: scala

给出方法

def twice(s: => Int): Int = s + s

我可以通过以下方式获得Function1类型(=> Int) => Int

val valTwiceA: (=> Int) => Int = twice
// or
val valTwiceC: (=> Int) => Int = {(byName/*:(=>Int)*/) => twice(byName)}

我想无法明确指定byName的类型。

  1. 我是对的吗?
  2. 明确指定byName类型的正确方法是什么? (byName: (=>Int))会产生错误“此处不允许使用名称参数类型”

  3. 代码模板:

    // scalaVersion "2.10.4" or "2.11.1"
    import org.scalatest.FreeSpec
    
    class ByNameTest extends FreeSpec {
      def twice(s: => Int): Int = s + s
      val valTwiceA: (=> Int) => Int = twice
      val valTwiceB: (=> Int) => Int = {byName => twice(byName)}
      val valTwiceC: (=> Int) => Int = {(byName/*:(=>Int)*/) => twice(byName)}
    
      "twice" in {
        val it = Iterator from 1
        assert(valTwiceA(it.next) === 3)
        assert(valTwiceB(it.next) === 7)
        assert(valTwiceC(it.next) === 11)
      }
    }
    

0 个答案:

没有答案