fork download
  1. import scala.util.Try
  2.  
  3. object Main extends App {
  4. def safePrint1[T](toString: T => String): PartialFunction[Any, Unit] = {
  5. case x: T => println(Try(toString(x)))
  6. }
  7.  
  8. def safePrint2[T : Manifest](toString: T => String): PartialFunction[Any, Unit] = {
  9. case x: T => println(Try(toString(x)))
  10. }
  11.  
  12. def iToS(x: Int) = s"$x.0"
  13. def bToS(x: Boolean) = if (x) "yes" else "no"
  14.  
  15. val printAny1 = safePrint1[Int](iToS) orElse safePrint1[Boolean](bToS)
  16. val printAny2 = safePrint2[Int](iToS) orElse safePrint2[Boolean](bToS)
  17.  
  18. printAny1(10)
  19. printAny1(true)
  20.  
  21. printAny2(10)
  22. printAny2(true)
  23. }
Success #stdin #stdout 0.37s 322432KB
stdin
Standard input is empty
stdout
Success(10.0)
Failure(java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Integer)
Success(10.0)
Success(yes)