【问题标题】:How do you define a type for a function in Scala?如何在 Scala 中为函数定义类型?
【发布时间】:2009-12-05 23:35:37
【问题描述】:

我希望有一种方法可以在 Scala 中为函数定义类型。

例如,假设我想要一个接受两个 Int 并返回一个布尔值的函数,我可以定义一个这样使用它的函数:

def checkInts(f: (Int,Int) => Boolean) = {
  // do stuff
}

有没有办法定义 f 的类型?然后我可以这样做:

def checkInts(f: MyFunctionType)

def checkInts(f: Option[MyFunctionType])

【问题讨论】:

    标签: scala function


    【解决方案1】:
    trait Foo {
      type MyFunction = (Int,Int) => Boolean
    
      def checkInts(f: MyFunction)
      def checkInts(f: Option[MyFunction])
    }
    

    【讨论】:

      【解决方案2】:

      补充原始答案:

      对于一些更复杂的情况,您可以使用还可以包含函数定义[1][2] 的结构类型。

      对于具体的例子和实际用法,函数类型可以很好地与Futures 一起使用,例如传递ExecutionContext 并在传递后实际执行异步函数。

      但是,请注意,如果您的 EC 始终在执行类中可用,因此您无需传递它,您可以使用别名参数(“给我一个 Future 结果”)[3] .

      下面的草稿示例显示了这个简单的想法:它有一个只有ec 的函数类型和一个结构类型,它也可以接受一些参数来执行函数。它还显示了具有按名称功能的替代方案:

      /** Define types in companion and sample functions that use them as args. */
      class Fun(implicit ec: ExecutionContext) {
        import Fun._
      
        def foo(fun: SimplyFun): Future[String] = fun()
        def bar(fun: StructuredFun): Future[String] = fun.buzz(fun.bee)
        def byNameBaz(fun: => Future[String]) = fun
      }
      
      object Fun {
        type SimplyFun = ExecutionContext => Future[String]
        type StructuredFun = {
          def buzz(bee: Int)(implicit ec: ExecutionContext): Future[String]
          val bee: Int
        }
      }
      
      // (somewhere outside)
      // example args could be instantiated as follows:
      val simpleArg: SimplyFun = _ => Future.successful(String)
      val structuredArg: StructuredFun = new {
        def buzz(bee: Int)(implicit ec: ExecutionContext) = Future.successful(s"$bee")
        val bee = 3
      }
      
      // ...and passed for execution along with the EC you like:
      import scala.concurrent.ExecutionContext.Implicits.global
      new Fun().foo(simpleArg)
      new Fun().bar(structuredArg)
      new Fun().byNameBaz(Future.failure(new RuntimeException))
      

      如果你想用一些逻辑来包装你的异步函数参数,这可能非常方便,例如类似事务的操作。

      【讨论】:

        猜你喜欢
        • 2011-11-05
        • 2017-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-03
        • 2016-06-24
        • 2022-06-15
        相关资源
        最近更新 更多