如果我具有以下类型和功能:
object M {
type X[Boolean] = Int => Boolean
def retrieveVal(x: X[Boolean]) : Boolean = //retrieve the Boolean value of x
}
我将如何获取并返回布尔值?
那是一个特殊的类型别名。它具有一个正式的类型参数(其名称无关紧要,因此对它的选择具有Boolean
误导性),用于定义从Int
到任意类型的函数。然后定义一个方法,retrieveVal
即采用一种特殊的X
恰好是X[Boolean]
(这里Boolean
是一个实际的类型参数,因此是在Boolean
我们熟悉),并返回一些Boolean
。但是,x
作为参数传递的函数需要一个Int
参数,并且没有证据。
因此,如果您retrieveVal
的定义是这样的:
def retrieveVal(i: Int, x: X[Boolean]): Boolean = ...
您可以这样定义它:
def retrieveVal(i: Int, x: X[Boolean]): Boolean = x(i)
以机智:
scala> type X[Boolean] = Int => Boolean
defined type alias X
scala> def retrieveVal(i: Int, x: X[Boolean]): Boolean = x(i)
retrieveVal: (i: Int, x: Int => Boolean)Boolean
scala> retrieveVal(23, i => i % 2 == 0)
res0: Boolean = false
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句