Skip to content

Instantly share code, notes, and snippets.

@itmammoth
Last active July 27, 2018 08:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itmammoth/077c26fc964cf4bd2e662184dcd76bc9 to your computer and use it in GitHub Desktop.
Save itmammoth/077c26fc964cf4bd2e662184dcd76bc9 to your computer and use it in GitHub Desktop.
kotlinでif文の条件に代入式を使いたい ref: https://qiita.com/itmammoth/items/e21dba17373e0aa7353e
if (val date = arguments?.getSerializable(ARG_DATE) as LocalDate) {
...
inline fun <T, R> ifNotNull(value: T?, thenPart: (T) -> R, elsePart: () -> R): R {
return if (value != null) {
thenPart(value)
} else {
elsePart()
}
}
val thenOrElse = ifNotNull(arguments?.getSerializable(ARG_DATE) as? LocalDate, {
// it => LocalDate
"then"
}, {
"else"
})
inline fun <T, R> ifNotNull(value: T?, thenPart: (T) -> R): R? {
return if (value != null) {
thenPart(value)
} else {
null
}
}
inline fun <T, R> ifNotNull(value: T?, thenPart: (T) -> R, elsePart: () -> R): R {
return if (value != null) {
thenPart(value)
} else {
elsePart()
}
}
@itmammoth
Copy link
Author

itmammoth commented Jul 20, 2018

You can write as below with this function.

val thenOrElse = ifNotNull(arguments?.getSerializable("date") as? LocalDate, {
    // it => LocalDate
    "then"
}, {
    "else"
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment