Created
          August 28, 2013 15:04 
        
      - 
      
 - 
        
Save seraphr/6367076 to your computer and use it in GitHub Desktop.  
    ScalaでTryとOption
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | scala> delete("hoge") | |
| res3: scala.util.Try[Unit] = Success(()) | |
| scala> delete("fuga") | |
| res4: scala.util.Try[Unit] = Failure(java.lang.IllegalArgumentException: cannot delete) | |
| scala> delete("piyo") | |
| res5: scala.util.Try[Unit] = Failure(java.util.NoSuchElementException: Predicate does not hold for None) | |
| scala> delete("etc") | |
| res6: scala.util.Try[Unit] = Failure(java.lang.IllegalArgumentException: cannot get) | |
| scala> deleteWithMatch("hoge") | |
| res7: scala.util.Try[Unit] = Success(()) | |
| scala> deleteWithMatch("fuga") | |
| res8: scala.util.Try[Unit] = Failure(java.lang.IllegalArgumentException: cannot delete) | |
| scala> deleteWithMatch("piyo") | |
| res9: scala.util.Try[Unit] = Failure(java.lang.IllegalArgumentException: not found) | |
| scala> deleteWithMatch("etc") | |
| res10: scala.util.Try[Unit] = Failure(java.lang.IllegalArgumentException: cannot get) | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import scala.util.Try | |
| case class Data(aId: String) | |
| def get(aId: String): Try[Option[Data]] = Try{ aId match { | |
| case "hoge" | "fuga" => Some(Data(aId)) | |
| case "piyo" => None | |
| case _ => throw new IllegalArgumentException("cannot get") | |
| }} | |
| def deleteData(aData: Data): Try[Unit] = Try{ aData match { | |
| case Data("hoge") => () | |
| case _ => throw new IllegalArgumentException("cannot delete") | |
| }} | |
| def delete(aId: String): Try[Unit] = { | |
| for{ | |
| Some(tData) <- get(aId) | |
| _ <- deleteData(tData) | |
| } yield () | |
| } | |
| def deleteWithMatch(aId: String): Try[Unit] = { | |
| get(aId) map { | |
| case Some(tData) => tData | |
| case None => throw new IllegalArgumentException("not found") | |
| } flatMap (deleteData) | |
| } | |
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment