0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

if文は式です【Kotlin】

Last updated at Posted at 2023-04-04

if文を式で扱わない場合

// 引数の値によって満車か空車を出力する関数
fun isParkingLotFull(carCount: int) {
	var text = ""
	if (carCount == 100) {
		text = "満車"
	} else {
		text = "空車"
	}
	println(text)
}
  • var text = ""の箇所が邪魔である

if文を式で扱う場合

// 引数の値によって満車か空車を出力する関数
fun isParkingLotFull(carCount: int) {
	val text = if (carCount == 100) {
		"満車"
	} else {
		"空車"
	}
	println(text)
}
  • if文が結果の値を返す!分かりやすい!
  • varval にできる!

さっきのコードをもっとシンプルに

// 引数の値によって満車か空車を出力する関数
fun isParkingLotFull(carCount: int) {
	val text = if (carCount == 100) "満車" else "空車"
	println(text)
}
  • 1行で記述できる!
  • Javaの三項演算子と一緒じゃない?

Q. じゃあ三項演算子で良くない?:thinking:

A. ダメです

この場合はいいのですが、ネストしたときに、三項演算子は激キモコードになります。

参考文献

Javaで三項演算子はどこまで許されるか

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?