如何测试对象不是scala中的函数

时间:2013-10-25 10:10:39

标签: function scala reflection types

我的问题非常简单:我希望将值隐式转换为函数,如果它们还不是函数。我计划通过请求实例化隐式参数来使用类型安全模式(如果值是隐式创建失败的函数)。 但是,我没有看到如何测试值不是函数

我在之前的一个问题中从用户Beryllium学习了类型安全模式。见: Type safe method chaining that doesn't allow repeats of operations

我实施的隐含工作正在进行,但也很好。我想自动将函数表达式转换为特定应用程序默认函数

 implicit def defaultExecutionUnitParameterNReturn(a: Any): Unit => MyDefaultReturn = 
{u : Unit => a }.andThen(_ => defaultReturn())

但是,如果用户将“a”实现为函数

,我的应用程序将失败

所以我的第一个想法是

 implicit def defaultExecutionUnitParameterNReturn[A](a: A)(implicit e : A =!= Function) Unit => MyDefaultReturn = 
{u : Unit => a }.andThen(_ => defaultReturn())
如果A和B是相同类型,则

其中implicit =!= [A,B]失败。 但“功能”不存在

2 个答案:

答案 0 :(得分:2)

您需要将隐式转化置于2个特征

trait Implicits extends ImplicitsLow {
  implicit def convertFunction[T, R](f: T => R) = ???
}

trait ImplicitsLow {
  implicit def convert[T](t: T) = ???
}

然后你可以观察到函数转换的使用优先于值1:

val result1: String = (i: Int) => i + 1
val result2: String = 1

// prints (function, value)   
println((result1, result2))

答案 1 :(得分:0)

调查下面的代码段。这是标准的隐式转换示例。 toFunnction0会收集任何内容并将其转换为Function0[R]或简化为() => R

implicit def toFunnction0[R](r: => R): Function0[R] = () => r

def iWantFunction0(f0: () => String) = {
  f0()
}

def testFun = {println("computing string in testFun..."); "ABC"} //every time when called block of code will run
val abcVal = "ABC" //this is computed only once

iWantFunction0(testFun)

//here abcVal is not a function, so implicit works. 
//toFunnction0 is in scope, so compiler will translate it into
//iWantFunction0(toFunnction0(abcVal))  
iWantFunction0(abcVal)