Optional Chaining Operator는 다양한 프로그래밍 언어에서 지원되고 있습니다. 각 언어에서의 사용 예시는 아래와 같습니다.
javascript// ECMAScript 2020 이상에서 지원
const person = {
name: 'John',
address: {
city: 'New York',
state: 'NY',
country: 'USA'
}
};
const zipCode = person?.address?.zipCode ?? 'N/A';
console.log(zipCode); // 'N/A'
typescriptinterface Person {
name: string;
address?: {
city: string;
state: string;
country: string;
}
}
const person: Person = {
name: 'John'
};
const zipCode = person?.address?.zipCode ?? 'N/A';
console.log(zipCode); // 'N/A'
javaclass Person {
private String name;
private Address address;
// 생성자, getter, setter 생략
public String getZipCode() {
return address?.getZipCode() ?? "N/A";
}
}
class Address {
private String city;
private String state;
private String country;
private String zipCode;
// 생성자, getter, setter 생략
}
Person person = new Person();
String zipCode = person.getAddress()?.getZipCode() ?? "N/A";
System.out.println(zipCode); // 'N/A'
pythonclass Person:
def __init__(self, name, address=None):
self.name = name
self.address = address
def get_zip_code(self):
return self.address?.get_zip_code() ?? 'N/A'
class Address:
def __init__(self, city, state, country, zip_code):
self.city = city
self.state = state
self.country = country
self.zip_code = zip_code
person = Person('John')
zip_code = person.address?.zip_code ?? 'N/A'
print(zip_code) # 'N/A'
kotlindata class Person(val name: String, val address: Address?)
data class Address(val city: String, val state: String, val country: String, val zipCode: String?)
fun getZipCode(person: Person): String {
return person.address?.zipCode ?: "N/A"
}
val person = Person("John", null)
val zipCode = person.address?.zipCode ?: "N/A"
println(zipCode) // 'N/A'