2016-07-05 23 views
3

私はDB内のあるオブジェクト(Fight)を見つけて、その存在に基づいてこの特定のオブジェクトを返すか、DB内に新しいオブジェクトを作成して新しく作成したオブジェクトを返したいと思います。Scalaの将来の内部の歩み

def findOrCreateFight(firstBoxer: BoxersRow, secondBoxer: BoxersRow, eventDate: java.sql.Date): Future[FightsRow] = { 
    for { 
    fight <- findByBoxersAndDate(firstBoxer, secondBoxer, eventDate) 
    } yield { 
    fight match { 
     case Some(f) => f 
     case None => createAndFindFight(firstBoxer, secondBoxer, eventDate) 
    } 
    } 
} 

findByBoxersAndDate関数はオブジェクト将来[FightsRow]オプション]を返し、createAndFindFight機能が将来[FightsRow]返す:私は、次の機能を実装しました。コンパイラは、createAndFindFight関数の行にエラーを表示します。

タイプが不一致です。見つかった: models.Tables.FightsRow

OKをので、私は 'ケースなし' で、この将来の完成結果を取得する必要があります: scala.concurrent.Futureは[models.Tables.FightsRow]必要。私はonComplete関数について考えましたが、Unitを返します.FitsRowオブジェクトは必要ありません。最高のスケーラブルな効果を得るために私の機能を修正する方法はありますか? :)

よろしく

答えて

1

PatrykĐwiekアイデア:

def findOrCreateFight(first: BoxersRow, second: BoxersRow, date: java.sql.Date): Future[FightsRow] = 
    findByBoxersAndDate(first, second, date).flatMap { 
    case None => createAndFindFight(first, second, date) 
    case Some(row) => Future.successful(row) 
    } 
+0

それは動作します!私は本当にあなたの助けに感謝します! – Gandalf

+0

@ガンダルフあなたの次のステップは、便利な回答をアップアップし、最高のものを受け入れることです。 –

3

さてさて、あなたは別のFutureなりますcreateAndFindFightから抜け出すだろう何。溶液? flatMapそれが、あなたはかなり適切な型にOption '&アンラップを変換' する必要があります:

findByBoxersAndDate(firstBoxer, secondBoxer, eventDate) 
    .flatMap(_.map(Future.successful).getOrElse(createAndFindFight(firstBoxer, secondBoxer, eventDate))) 

または、直接のため-理解あなたにマッチする:

for { 
    potentialFight <- findByBoxersAndDate(firstBoxer, secondBoxer, eventDate) 
    actualFight <- potentialFight match { 
     case Some(f) => Future.successful(f) 
     case None => createAndFindFight(firstBoxer, secondBoxer, eventDate) 
    } 
} yield actualFight 

免責事項:上記のコードはテストされていません:)

+0

それは機能します!あなたの提案をありがとう! :) – Gandalf