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?

inline関数の考え方

Posted at

はじめに

今回はあまり使われてないがすごい便利なインライン関数での考え方を紹介していきます
そもそも、Inline関数は特定の処理を関数内で展開できるようにするものでほとんど同じ処理をしている関数を無駄に増やさないためによく使われます

コード

今回は例としてEpoch秒数を更新する処理で考えてみます

private inline fun updateEpochSecond(
    isStart: Boolean,
    // LocalDate,LocalTimeはこの関数を呼び出す側で利用できるもの、尚且つLongが返却物にないとダメ
    crossinline updateFunc: (LocalDate, LocalTime) -> Long
) {
    val zone = ZoneId.systemDefault()
    val currentEpoch = if (isStart) _uiState.value.startEpochSecond else _uiState.value.endEpochSecond
    val zonedDateTime = Instant.ofEpochSecond(currentEpoch).atZone(zone)
    val currentDate = zonedDateTime.toLocalDate()
    val currentTime = zonedDateTime.toLocalTime()

// ここまでの処理で用意した値をcrosslineに渡すことで呼び出し元で別の加工ができる
    val newEpoch = updateFunc(currentDate, currentTime)

// 帰ってきた値を使って更新
    _uiState.value = if (isStart) {
        _uiState.value.copy(startEpochSecond = newEpoch)
    } else {
        _uiState.value.copy(endEpochSecond = newEpoch)
    }
}

fun updateDate(date: LocalDate, isStart: Boolean) {
    updateEpochSecond(isStart) { _, time ->
        date.atTime(time).atZone(ZoneId.systemDefault()).toEpochSecond()
    }
}

fun updateTime(time: HourMinute, isStart: Boolean) {
    updateEpochSecond(isStart) { date, _ ->
        time.toDateTime(date).atZone(ZoneId.systemDefault()).toEpochSecond()
    }
}

さいごに

高次関数と似てはいますがInline関数はパフォーマンスにも影響するので使えるところは使っていきたいですね

0
0
0

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?