[英]How do you define a type for a function in Scala?
我希望有一种方法可以为Scala中的函数定义类型。
例如,假设我想要一个需要两个Ints并返回一个布尔值的函数,我可以定义一个使用它的函数:
def checkInts(f: (Int,Int) => Boolean) = {
// do stuff
}
有没有办法定义f的类型? 然后我可以这样做:
def checkInts(f: MyFunctionType)
要么
def checkInts(f: Option[MyFunctionType])
trait Foo {
type MyFunction = (Int,Int) => Boolean
def checkInts(f: MyFunction)
def checkInts(f: Option[MyFunction])
}
增加原来的答案:
对于一些更复杂的情况,您可以使用结构类型,也可以包括函数定义[1] , [2] 。
至于特定的例子和实际用法,函数类型可以很好地用于Future
s,例如传递ExecutionContext
并在传递后实际执行异步函数。
但是,请注意,如果您始终在执行类中使用EC,因此您无需传递它,则可以使用按名称参数(“gimme just a Future
result”) [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))
如果你想用一些逻辑包装async函数参数,例如类似事务的操作,这可能非常方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.