给出方法
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
的类型。
byName
类型的正确方法是什么?
(byName: (=>Int))
会产生错误“此处不允许使用名称参数类型”
代码模板:
// 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)
}
}