LoginSignup
1
2

More than 5 years have passed since last update.

Kotlin 1.1で要素が空の時のaverage()が0.0を返す仕様からDouble.NaNを返すように変わった

Last updated at Posted at 2017-04-02

 Whats's New Kotlin 1.1にも載っていないマイナーな変更。

 Collection<T>Array<T>Iterable<T>の拡張関数、average

 この関数の、要素が空の時の返り値がKotlin 1.1で変わりました。

 Kotlin 1.0では次のように、0.0を返します。

@Test
fun test1() {
    val result = emptyList<Int>().average()
    Assert.assertTrue(result == 0.0)
}

 Kotlin 1.1では、Double.NaNを返します。

@Test
fun test1() {
    val result = emptyList<Int>().average()
    Assert.assertTrue(result.isNaN())
}

 IssueはこちらのKT-15399

Iterable.max() and Iterable.average() have different behavior when run on empty collections; max() returns null, but average() returns zero. These should have the same behavior. I believe that returning null is the correct behavior, since the average of "nothing" is not "zero".

 私個人の意見としてはこの方が言っている通り、averageも要素が空の時はnullを返すべきだと思います。ただ、それだと返り値型をDouble?に変更しないといけないので破壊的な変更になってしまいます。そのためKotlin 1.1の変更では、Double.NaNにしたのでしょうかね?

 変更コミットはこちらIterable<T>Array<T>Collection<T>Sequence<T>average()の実装が変更されています。

 ChangeLogには載ってましたね。

1
2
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
1
2