[Android] 多個 null 物件處理 — 快速找出不是 null 的它!!

Kuang Lin
2 min readDec 5, 2018

--

今天遇到一個常見的問題:

如果我有三個 String:

private void example(String a, String b, String c) {}

這時候如果我們想要在 a, b, c 中快速確定誰是 null、 誰不是,我們當然可以用老招:

if (a == null) …if (b == null) …if (c == null) …

但如果我們要做的是連續的邏輯判斷例如:

if  (a == null) {    if (b == null) {
if (c == null) // do somthing
}
}

這樣在程式碼裡面就到處都會有這種惱人的波動拳

於是找了一些大神的方法,Android 的 Guava 裡有提供一個 Option 的物件,

操作方法如下:

String d= Optional.fromNullable(a).or(Optional.fromNullable(b)).or(Optional.fromNullable(c)).orNull;

這樣 String d 就可以直接得到第一個出現不是 null 的物件了!!

P.S.1 如果 a, b, c 三者都是 null 的話,最後就會在 orNull 上面噴出 null !

P.S. 2 如果最後只寫上 or(Optional.fromNullable(b)) 沒有加上 orNull,那回傳的物件就會是 Optional 型別,而不是 String 型別。

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Kuang Lin
Kuang Lin

No responses yet

Write a response