Last active
July 27, 2018 08:08
-
-
Save itmammoth/077c26fc964cf4bd2e662184dcd76bc9 to your computer and use it in GitHub Desktop.
kotlinでif文の条件に代入式を使いたい ref: https://qiita.com/itmammoth/items/e21dba17373e0aa7353e
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (val date = arguments?.getSerializable(ARG_DATE) as LocalDate) { | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inline fun <T, R> ifNotNull(value: T?, thenPart: (T) -> R, elsePart: () -> R): R { | |
return if (value != null) { | |
thenPart(value) | |
} else { | |
elsePart() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val thenOrElse = ifNotNull(arguments?.getSerializable(ARG_DATE) as? LocalDate, { | |
// it => LocalDate | |
"then" | |
}, { | |
"else" | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inline fun <T, R> ifNotNull(value: T?, thenPart: (T) -> R): R? { | |
return if (value != null) { | |
thenPart(value) | |
} else { | |
null | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inline fun <T, R> ifNotNull(value: T?, thenPart: (T) -> R, elsePart: () -> R): R { | |
return if (value != null) { | |
thenPart(value) | |
} else { | |
elsePart() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can write as below with this function.