Raku의 is required — 꼭 채워야 하는 속성(attribute)
Raku의 is required — 꼭 채워야 하는 속성(attribute)
어떤 속성은 객체를 만들 때 반드시 값을 줘야 하는 "필수" 속성으로 지정하고 싶을 때가 있어요. 비밀번호 같은 데이터를 잊고 빠뜨리면 프로그램이 오작동하니까, 만들 때부터 강제해 두면 안전하죠. is required 트레잇이 그 역할을 해요.
multi trait_mod:<is>(Attribute $attr, :$required!)
multi trait_mod:<is>(Parameter:D $param, :$required!)
클래스나 역할의 속성을 필수로 표시합니다. 객체 생성 시점에 그 속성이 초기화되지 않으면 X::Attribute::Required 예외가 던져져요.
class Correct {
has $.attr is required;
}
say Correct.new(attr => 42);
# OUTPUT: «Correct.new(attr => 42)»
class C {
has $.attr is required;
}
C.new;
CATCH { default { say .^name => .Str } }
# OUTPUT: «X::Attribute::Required => The attribute '$!attr' is required, but you did not provide a value for it.»
Correct는 attr => 42처럼 값을 줘서 정상적으로 만들어지지만, C는 값을 주지 않고 C.new만 호출하니 X::Attribute::Required 예외가 나와요.
비공개 속성이라도 같은 규칙이 적용돼요.
class D {
has $!attr is required;
}
D.new;
CATCH { default { say .^name => .Str } }
# OUTPUT: «X::Attribute::Required => The attribute '$!attr' is required, but you did not provide a value for it.»
has $.attr is required든 has $!attr is required든, 값을 안 주면 동일한 예외가 발생합니다. 공개·비공개 여부와 상관없이 필수라는 표시가 우선인 거죠.
왜 필수인지 이유를 인자로 줄 수도 있어요.
class Correct {
has $.attr is required("it's so cool")
};
say Correct.new();
# OUTPUT: «The attribute '$!attr' is required because it's so cool,but you did not provide a value for it.»
required(...)로 이유를 붙이면, 그 내용이 예외 메시지에 그대로 들어가서 "왜 값을 줘야 하는지"가 사용자에게 더 분명하게 전달돼요.