1

Any idea why the following code wouldn't compile?

fun <T : Comparable<T>> naturalSort(list: List<T>): List<T> {
  val natComparator = naturalOrder<T>() // compiler error here

  return list.sortedWith(natComparator)
}

The second line results in the compiler error:

Type argument is not within its bounds: should be subtype of 'Comparable'

Update: It works for me in https://play.kotlinlang.org/ but fails in Eclipse and when building the project (from Eclipse) with the project's Gradle build script.

Here's how my Gradle build environment looks like:

https://pastebin.com/0GDUWy2C

Sdf
  • 79
  • 1
  • 6
  • 4
    Which version of Kotlin are you using? Seems to work fine for me. – Logain Aug 08 '19 at 01:19
  • 1
    Same here: no problems, works as expected: https://pl.kotl.in/rwy-h4b97 –  Aug 08 '19 at 01:20
  • It works for me too in https://play.kotlinlang.org/ but fails in Eclipse and when building the project (from Eclipse) with the project's Gradle build script. Here's how my Gradle build environment looks like: https://pastebin.com/0GDUWy2C – Sdf Aug 08 '19 at 15:34

2 Answers2

0

Solved. The problem was caused by the wrong Comparable interface being used due to import statements in the actual code (no problem with the import statements, not really sure why java.lang.Comparable was used instead of kotlin.Comparable). Specifying in the code that kotlin.Comparable should be used resolves the issue:

fun <T : kotlin.Comparable<T>> naturalSort(list: List<T>): List<T> { val natComparator = naturalOrder<T>() // no error return list.sortedWith(natComparator) }

Thanks to everyone who responded.

Sdf
  • 79
  • 1
  • 6
  • I guess you may be interested in this discussion: https://stackoverflow.com/questions/147454/why-is-using-a-wild-card-with-a-java-import-statement-bad –  Aug 09 '19 at 00:40
  • 2
    Actually, no wildcard imports or excessive imports were used (6 classes imported total), that's why it was so surprising. – Sdf Aug 09 '19 at 03:15
0

Might not be relevant to this case but maybe someone would have the similar case as me: I had a similar problem with Mui Material components (for Autocomplete and Textfield). For me the solution was to suppress the warnings. This was my code:

Autocomplete<AutocompleteProps<String>> { ... }

This was the error I was getting:

Type argument is not within its bounds: should be subtype of 'ChildrenBuilder'

And the solution for me was to add this suppress before the view's class declaration:

@Suppress("UPPER_BOUND_VIOLATED")