条件でのNULL処理の使用
条件文がNULL値でどのように動作するかを理解することで、コード行の追加を回避できます。 変数someFlagがnullの可能性があるブール変数である場合、次の条件付きブロックはsomeFlagがtrueの場合にのみ実行されます。
String
変数には、null
、空の文字列(""
)または少なくとも1つの文字を含めることができます。 変数middleName
がString
の場合、次の条件付きブロックは、middleName
がnull
ではなく、少なくとも1文字を含む場合にのみ実行されます:
// If customer has a middle name...
if (middleName) {
// Do something here if middleName has at least one character in it
}
変数recentOrders
がList
の場合、次の条件付きブロックは、recentOrders
がnull
ではなく、少なくとも1つの要素が含まれている場合にのみ実行されます:
// If customer has any recent orders...
if (recentOrders) {
// Do something here if recentOrders has at least one element
}
変数
recentTransactions
がMap
の場合、次の条件付きブロックは、recentTransactions
がnull
ではなく、マップ・エントリが少なくとも1つ含まれている場合にのみ実行されます:// If supplier has any recent transactions...
if (recentTransactions) {
// Do something here if recentTransactions has at least one map entry
}
変数
customerId
をnull
にでき、そのデータ型が前述のもの以外である場合、次の条件付きブロックは、customerId
にnull
以外の値がある場合にのみ実行されます:// If non-boolean customerId has a value...
if (customerId) {
// Do something here if customerId has a non-null value
}
条件付きで
Map
エントリをテストする必要があり、Map
がnull
である可能性がある場合は、マップ・キーを名前で参照するときに安全ナビゲーション演算子(?.
)を使用してください:// Use the safe-navigation operator in case options Map is null
if (options?.orderBy) {
// Do something here if the 'orderBy' key exists and has a non-null value
}