Kotlin 型の不一致エラー

実現したいこと

エラーを解決したい

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

変数listがList<Int?>と判定されているようです。
標準入力で受け取った変数aをMutableList<Int>に変換しているにもかかわらず、なぜそうならないのか原因がわかりません。

Main.kt:17:7: error: type mismatch: inferred type is List<Int?> but MutableList<Int> was expected list -= list.maxBy{it} ^ Main.kt:20:7: error: type mismatch: inferred type is List<Int?> but MutableList<Int> was expected 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> = mutableListOf()5 for (i in a) {6 if (i != null) {7 list.add(i)8 }9 }10 11 var listA: MutableList<Int?> = mutableListOf()12 var listB: MutableList<Int?> = mutableListOf()13 14 for (i in 1..N) {15 if (i%2 == 0) {16 listB.add(list.maxBy{it})17 list -= list.maxBy{it}18 } else {19 listA.add(list.maxBy{it})20 list -= list.maxBy{it}21 }22 }23 24 var resultA: Int? = 025 var resultB: Int? = 026 27 if (resultA != null) {28 for (i in listA) {29 resultA += i!!30 }31 }32 33 if (resultB != null) {34 for (i in listB) {35 resultB += i!!36 }37 }38 39 if (resultA != null && resultB != null) {40 val result = resultA - resultB 41 println("$result")42 }43 44}

コメントを投稿

0 コメント