Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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.
- 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().
- */
- import android.util.Log
- fun expect(condition: Boolean, tag: String) {
- expect(condition, tag, "Expectation was broken.")
- }
- fun expect(condition: Boolean, tag: String, message: String) {
- if (!condition) {
- Log.e(tag, message)
- }
- }
- fun require(condition: Boolean) {
- require(condition, "Assertion failed!")
- }
- fun require(condition: Boolean, message: String) {
- if (!condition) {
- throw AssertionError(message)
- }
- }
- /*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.
- expects() logs the error but won't crash the app. This is good for documenting non-critical expectations.*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement