Advertisement
ulfben

assert(), require(), expect()

Sep 5th, 2021
1,339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.39 KB | None | 0 0
  1. /*
  2. I habitually put assert()-statements in my code to check for programmer errors. When an assert() triggers it crashes the application immediately so the programmer error can be fixed. Problem is: assert() doesn't actually exist in the Android Java runtime (ART)! You can try it yourself - put assert(false) in your (Java) Game constructor and run it - nothing happens! Not in debug mode, not on the emulator nor on the physical device.
  3.  
  4. Kotlin *does* provide an Assert, but it doesn't make it easy to provide a helpful message. So I use two utility functions to provide assertion with messaging: require() and expect().
  5. */
  6.  
  7. import android.util.Log
  8. fun expect(condition: Boolean, tag: String) {
  9.     expect(condition, tag, "Expectation was broken.")
  10. }
  11.  
  12. fun expect(condition: Boolean, tag: String, message: String) {
  13.     if (!condition) {
  14.         Log.e(tag, message)
  15.     }
  16. }
  17.  
  18. fun require(condition: Boolean) {
  19.     require(condition, "Assertion failed!")
  20. }
  21.  
  22. fun require(condition: Boolean, message: String) {
  23.     if (!condition) {
  24.         throw AssertionError(message)
  25.     }
  26. }
  27.  
  28. /*requires() will throw an AssertionError and thus be functionally equivalent to the original assert(). Your application will crash, and the debugger will give you a stack trace to show where the fault was.
  29.  
  30. expects() logs the error but won't crash the app. This is good for documenting non-critical expectations.*/
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement