Kotlin 연산 자 는 아버지의 아들 의 개 이름 을 빠르게 가 져 옵 니 다.

19922 단어 Android
NPE (NullPointer Exception) 는 가장 저급 하고 범 하기 쉬 운 실수 이자 가장 즐겨 만 나 는 버그 이기 도 하 다.본 고 는 Kotlin 입문 귀 요 미 에 게 적합 합 니 다. 큰 사람 이 가볍게 뿌 립 니 다. 하하 하!
물음표 N 중대 가 빈 칸 으로 처리 해 줄 게 (?)
서버 에서 json 에 여러 가지 데 이 터 를 끼 워 넣 었 다 면 POJO 로 비 추 는 것 은 다음 과 같 습 니 다.
//        getter setter
public class TestParent {
    private TestChild child;

    public class TestChild {
        private List<TestDog> dogs;

        public class TestDog {
            private String name;
        }
    }
}

그리고 아버지 아들 의 첫 번 째 개 이름 이 뭔 지 알 기 위해 서 는 이렇게 해 야 합 니 다.
if (parent != null) { //   
    TestParent.TestChild child = parent.getChild();
    if (child != null) { //    
        List<TestParent.TestChild.TestDog> dogs = child.getDogs();
        if (dogs != null && !dogs.isEmpty()) {
            TestParent.TestChild.TestDog dog0 = dogs.get(0);
            if (dog0 != null) { //   
                System.out.println("name:" + dog0.getName());
            }
        }
    }
}

초보 자 들 은 대부분 이렇게 씁 니 다. 오 마 이 갓, 이 건 너무 비대 하고 못 생 긴 코드 입 니 다. 줄 수 를 모 으 기 때문에 저 는 최적화 하기 로 했 습 니 다. (자바 8 의 API 는 고려 하지 않 습 니 다) 가능 한 한 if 내장 을 줄 이기 로 했 습 니 다.
TestParent.TestChild child = parent != null ? parent.getChild() : null;
List<TestParent.TestChild.TestDog> dogs = child != null ? child.getDogs() : null;
TestParent.TestChild.TestDog dog0 = (dogs != null && !dogs.isEmpty()) ? dogs.get(0) : null;
if (dog0 != null) System.out.println("name:" + dog0.getName());

이런 분할 은 간결 하지만 가 독성 을 잃 고 반응 이 느 린 학생 들 은 잠시 동안 무엇 을 하고 있 는 지 알 수 없다.그럼 Kotlin 의 "?" (빈 처리 연산 자) 로 어떻게 할 까요?
println("name:" + parent?.child?.dogs?.firstOrNull()?.name)

둥지 풀, 바로 한 줄 이면 돼!내 가 이 코드 를 처음 썼 을 때, 나 는 이 빌어먹을 Kotlin 문법 사탕 에 기절 했다.조금 만 설명 하 겠 습 니 다. 1. println 은 Kotlin 의 내 장 된 함수 로 자바 의 sout 와 같 습 니 다.2. 여기 서 Kotlin 집합 클래스 에 내 장 된 함수 firstOrNull 을 사 용 했 습 니 다. 말 그대로 집합 하 러 가 는 첫 번 째 라 는 것 을 알 고 못 찾 으 면 null 로 돌아 갑 니 다.3、? 연산 자의 의 미 는 왼쪽 값 이 비어 있 는 지 여 부 를 판단 하 는 것 입 니 다. 비어 있 지 않 으 면 뒤의 xxx 호출 을 계속 합 니 다. 여 기 는 체인 호출 입 니 다. 체인 에 한 부분 이 비어 있 으 면 전체 표현 식 이 비어 있 습 니 다.4. 위의 자바 코드 를 결합 하여 보면 사실 Kotlin 의 빈 처리 연산 자 는 자바 판단 의 세 가지 연산 자 를 간소화 한 것 이기 때문에 저 는 자바 에서 도 한 줄 을 소란 을 피 울 수 있 습 니 다.
System.out.println("name:" + (((parent != null ? parent.getChild() : null) != null ? parent.getChild().getDogs() : null) != null ? (!parent.getChild().getDogs().isEmpty() ? (parent.getChild().getDogs().get(0) != null ? parent.getChild().getDogs().get(0).getName() : null) : null) : null));
//   ,    ?              ,                 !

당신 은 당신 의 대상 이 비어 있 지 않다 고 확신 합 니 다 (!)
빈 처리 와 는 반대로!!조작 부호 의 의 미 는 비 공 단언 입 니 다. 예 를 들 어 이 조작 부호 의 차이 가 있 는 지 확인 하 겠 습 니 다. 빈 검사 가 필요 합 니 다.
val files = File("/sdcard/Android").listFiles()
if (files != null) {
	for(f in files) {
		println(f.name)
	}
}

빈 검사 가 필요 없습니다.
val files = File("/sdcard/Android").listFiles()!!
for(f in files) {
	println(f.name)
}

시간 이 없 는 사람 은 누 구 를 쓴다 (?:)
상용 코드 블록 먼저 보기:
public static void showSoftInput(Context context) {
    if (context instanceof Activity) {
        View view = ((Activity) context).getCurrentFocus();
        if (view == null) {
            view = new View(context);
        }
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (null != imm) {
            view.requestFocus();
            imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        }
    }
}

이 view 는 getCurrent Focus 를 통 해 가 져 오 려 고 시도 합 니 다. 가 져 오지 못 하면 new.이와 같은 조작 은 너무 흔 하 다. 심지어 몇 층 을 끼 워 넣 은 것 도 있다.Elvis 연산 자 (?:) 로 어떻게 실현 합 니까?
fun showSoftInput(context: Context) {
    if (context is Activity) {
        val view = (context.currentFocus ?: View(context)).apply { requestFocus() }
        (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).apply {
            showSoftInput(view, InputMethodManager.SHOW_FORCED)
        }
    }
}

좋은 웹페이지 즐겨찾기