require vs assert
require
- predifined function
- if
requireis false, throwIllegalArgumentException
class Rational(x: Int, y: Int) {
require(y>0, "denominator must be positive")
}
val errorValue = new Rational(1,0)
// java.lang.IllegalArgumentException: requirement failed: denominator must be positive
// ...
assert
- if
assertis false, throwAssertionError
val a = sqrt(y)
assert(x>=0)
difference
requireis used to enforce a precondition on the caller of a function.- function을 부를 때, 컨디션 체크.
- Excetion 메시지에서도 볼 수 있듯, argument가 잘못된 것.
- (비유) HTTP로 따지자면.. 400 bad request
assertis used as to check the code of the function itself.function에서 온 값을 비교
(비유) HTTP로 따지자면.. 500 internal server error