
Javaで作った 入力受付アプリ を Kotlin で実装してみました。
そんな中で必要になった、Kotlinでの
- 関数
- if文
- when文
この3つにフォーカスを当てて紹介します!
Kotlinでの関数の書き方
Int型の年齢を受け取って、String型の年齢区分を返す
selectAgeCategory
という名前の関数を定義するとこうなります。
fun selectAgeCategory(age: Int): String {
//処理内容
}
fun 関数名(引数: 引数の方): 戻り値の型 {}
関数の定義の基本形はこうなります。
関数の定義の際は、頭に 『fun』 と付けて定義します。
functionの fun ですね!
selectAgeCategoryの詳細
private fun selectAgeCategory(age: Int): String {
Log.d(TAG, "Inputted age : $age")
return when {
age < 0 -> "不正な年齢"
age in 0..14 -> "幼少期"
age in 15..29 -> "青春期"
age in 30..44 -> "朱夏期"
age in 45..59 -> "白秋期"
age in 60..75 -> "玄冬期"
else -> "高齢期"
}
}
クラス内からのみアクセスを許可するように、
アクセス修飾子の private を付けています。

When文の書き方
When文はJavaでのSwitch文のような働きをします。
val ageCategory = when {
age < 0 -> "不正な年齢" /* ageが0未満の時 */
age in 0..14 -> "幼少期" /* ageが0以上14以下の時 */
age in 15..29 -> "青春期" /* ageが15以上29以下の時 */
age in 30..44 -> "朱夏期" /* ageが30以上44以下の時 */
age in 45..59 -> "白秋期" /* ageが45以上59以下の時 */
age in 60..75 -> "玄冬期" /* ageが60以上75以下の時 */
else -> "高齢期" /* ageが以上のどれにも当てはまらない時 */
}
in min .. max と書くことで min以上 max以下 という条件を実現することができます。
age < 0 -> "不正な年齢"
age != 0 -> "hoge"
age == 0 -> "hoge"
上記のように、比較演算子を利用することも可能です。
Javaのswitch文より融通が効いて、柔軟に条件に対応することが可能です。
例
when (age) {
in 0..14 -> println("a is in the range")
!in 0..14 -> println("a is outside the range")
else -> println("otherwise")
}

if文の書き方
今回のWhen文は長くなりあまりカッコよくないですが、if文で書くことも可能です。
private fun selectAgeCategory(age: Int): String {
Log.d(TAG, "Inputted age : $age")
var ageCategory = ""
if (age < 0) {
ageCategory = "不正な年齢"
} else if (age < 15) {
/* 0 ~ 14歳 */
ageCategory = "幼少期"
} else if (age < 30) {
/* 15 ~ 29歳 */
ageCategory = "青春期"
} else if (age < 45) {
/* 30 ~ 44歳 */
ageCategory = "朱夏期"
} else if (age < 60) {
/* 45 ~ 59歳 */
ageCategory = "白秋期"
} else if (age < 75) {
/* 60 ~ 74歳 */
ageCategory = "玄冬期"
} else {
/* 75歳 ~ */
ageCategory = "高齢期"
}
return ageCategory
}
サンプルアプリの概要とコード

年齢を入力すると、応じた年齢区分が表示されます。
以下にソースコードを貼っておくので、参考になれば幸いです。
ご精読ありがとうございました!!
レイアウトxml : first_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="@+id/first_fragment_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/armata"
android:text="年齢を入力してください"
android:textColor="#001D74"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.296" />
<EditText
android:id="@+id/input_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:fontFamily="@font/armata"
android:gravity="center"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.483"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.373" />
<Button
android:id="@+id/age_category_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#00BCD4"
android:text="年齢区分"
android:textColor="#FFFFFF"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/age_category_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/armata"
android:text=""
android:textColor="#001D74"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.655" />
</androidx.constraintlayout.widget.ConstraintLayout>
ロジック部 : FirstFragment.kt
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.first_fragment.*
class FirstFragment : Fragment() {
companion object {
private const val TAG = "FirstFragment"
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.first_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val ageCategoryButton = age_category_button
val editText = input_age
val ageCategoryResult = age_category_result
ageCategoryButton.setOnClickListener {
Log.d(TAG, "ageCategoryButton pressed!")
/* ボタンクリックのタイミングでキーボードを閉じる */
val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
if (TextUtils.isEmpty(editText.text.toString())) {
/* 入力欄が空であれば何もしない */
Log.d(TAG, "Input age is empty.")
return@setOnClickListener
}
val inputAge = Integer.parseInt(editText.text.toString())
val ageCategory = selectAgeCategory(inputAge)
ageCategoryResult.text = ageCategory
}
}
private fun selectAgeCategory(age: Int): String {
Log.d(TAG, "Inputted age : $age")
return when {
age < 0 -> "不正な年齢"
age in 0..14 -> "幼少期"
age in 15..29 -> "青春期"
age in 30..44 -> "朱夏期"
age in 45..59 -> "白秋期"
age in 60..75 -> "玄冬期"
else -> "高齢期"
}
}
}
ピンバック: Kotlinオサレ説【ゆるいです】【モダン⭐︎プログラマ】 | Memento Mori Blog