【问题标题】:How to test that an object is not a function in scala如何测试一个对象不是scala中的函数
【发布时间】:2013-11-04 09:40:42
【问题描述】:

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

我在之前的一个问题中从用户 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 是同一类型,则隐式 =!=[A,B] 会失败。 但“功能”不存在

【问题讨论】:

  • Coo,请粘贴您的代码。您如何尝试将对象转换为函数以及如何失败?
  • 我对类型安全模式感兴趣还是你的意思是类型类?
  • 请不要使用“object”这个词作为“value”的同义词,因为在 Scala 中 object 是创建特殊类型值的关键字。其次,不要将“函数”用作“方法”的同义词,因为它们在 Scala 中完全不同,只有 FunctionN 是一流的值。当您忽略这些区别时,您的问题就会变得模棱两可且难以解释。
  • @Randall Schulz:你绝对正确,我将“对象”更正为“价值”。正确使用了“函数”。
  • @AlexIv 帖子已编辑,带有类型安全模式的链接

标签: function scala reflection types


【解决方案1】:

您需要将隐式转换放在 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))

【讨论】:

  • 隐式级联?这对我来说是个新闻!
【解决方案2】:

调查下面的代码被剪断。这是标准的隐式转换示例。 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)  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    相关资源
    最近更新 更多