Kotlin 型の不一致エラー

実現したいこと

エラーを解決したい

発生している問題・エラーメッセージ

型の不一致でエラーとなっているようです。

例えば、1つ目のMain.kt:11:22に対するエラーですが、
list.maxBy{it}の返り値がInt?なので、add先のlistBをMutablelist<Int?>としていますが、これのどこがいけないのか分かりません。

Main.kt:11:22: error: type parameter bound for R in inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R): T? is not satisfied: inferred type Int? is not a subtype of Comparable<Int?> listB.add(list.maxBy{it}) ^ Main.kt:12:12: error: assignment operators ambiguity: public operator fun <T> Iterable<Int?>.minus(element: Int?): List<Int?> defined in kotlin.collections public inline operator fun <T> MutableCollection<in Int?>.minusAssign(element: Int?): Unit defined in kotlin.collections list -= list.maxBy{it} ^ Main.kt:14:22: error: type parameter bound for R in inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R): T? is not satisfied: inferred type Int? is not a subtype of Comparable<Int?> listA.add(list.maxBy{it}) ^ Main.kt:15:12: error: assignment operators ambiguity: public operator fun <T> Iterable<Int?>.minus(element: Int?): List<Int?> defined in kotlin.collections public inline operator fun <T> MutableCollection<in Int?>.minusAssign(element: Int?): Unit defined in kotlin.collections list -= list.maxBy{it} ^

該当のソースコード

kotlin

1fun main(args: Array<String>) {2 val N = readLine()!!.toInt()3 val a = readLine()!!.split(" ").map{it.toInt()}4 var list: MutableList<Int?> = a.toMutableList()5 6 var listA: MutableList<Int?> = mutableListOf()7 var listB: MutableList<Int?> = mutableListOf()8 9 for (i in 1..N) {10 if (i%2 == 0) {11 listB.add(list.maxBy{it})12 list -= list.maxBy{it}13 } else {14 listA.add(list.maxBy{it})15 list -= list.maxBy{it}16 }17 }18 19 var resultA: Int? = 020 var resultB: Int? = 021 22 if (resultA != null) {23 for (i in listA) {24 resultA += i!!25 }26 }27 28 if (resultB != null) {29 for (i in listB) {30 resultB += i!!31 }32 }33 34 if (resultA != null && resultB != null) {35 val result = resultA - resultB 36 println("$result")37 }38 39}

コメントを投稿

0 コメント