1

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

在我之前的一个问题中,我从用户 Beryllium 那里学习了类型安全模式。请参阅: 不允许重复操作的类型安全方法链接

我实现的隐式正在工作,但太好了。我想自动将非函数表达式转换为特定应用程序默认函数

 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 是同一类型,则隐式 =!=[A,B] 失败。但“功能”不存在

4

2 回答 2

2

您需要将隐式转换放在 2 个特征中

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

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

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

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

// prints (function, value)   
println((result1, result2))
于 2013-10-25T10:50:31.997 回答
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)  
于 2013-10-25T11:00:59.147 回答