web-dev-qa-db-ja.com

Scalaで関数の型をどのように定義しますか?

Scalaで関数の型を定義する方法があることを願っています。

たとえば、2つのIntを受け取り、ブール値を返す関数が必要な場合、次のようにそれを使用する関数を定義できます。

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

Fの型を定義する方法はありますか?それから私は次のようなことをすることができます:

def checkInts(f: MyFunctionType)

または

def checkInts(f: Option[MyFunctionType])
39
Alex Black
trait Foo {
  type MyFunction = (Int,Int) => Boolean

  def checkInts(f: MyFunction)
  def checkInts(f: Option[MyFunction])
}
46
Mitch Blevins

元の答えを補強するには:

さらに複雑なケースでは、関数の定義 [1][2] を含めることもできる構造型を使用できます。

特定の例と実際の使用法については、関数タイプはFuturesで非常にうまく使用できます。 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))

これは、非同期関数の引数をいくつかのロジックでラップする場合に非常に便利です。トランザクションのような操作。

0
Vladimir Salin