Guest User

Untitled

a guest
Apr 21st, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. object AutoCloseableUtils {
  2.  
  3. /**
  4. * Class provides try-with-resource for scala
  5. * Basic tool for resource management.
  6. * This class is similar to try-with-resources in java.
  7. *
  8. * @param resource Produces the resource
  9. * @tparam R Resource type
  10. */
  11. implicit class AutoCloseableResource[R <: AutoCloseable](resource: R){
  12.  
  13. /**
  14. * Method performs a block on resource and returns the value.
  15. * Resource will be closed automatically.
  16. *
  17. * @param block An action to be performed on resource
  18. * @tparam A Return type
  19. */
  20. @inline
  21. def use[A](block: (R => A)): A = {
  22. try {
  23. block(resource)
  24. } finally {
  25. if (resource != null) try {
  26. resource.close()
  27. } catch {
  28. case e: Exception => e.printStackTrace()
  29. }
  30. }
  31. }
  32.  
  33. }
  34.  
  35. }
Add Comment
Please, Sign In to add comment