kotlin エラー「error: type mismatch: inferred type is Int but Boolean was expected」の解決方法

kotlin エラー「error: type mismatch: inferred type is Int but Boolean was expected」の解決方法

kotlinで、エラー「error: type mismatch: inferred type is Int but Boolean was expected」の解決方法を記述してます。比較演算子の記述ミスなどに発生します。

環境

  • OS windows11 home
  • java 17.0.2
  • kotlin 1.6.10-release-923

エラー全文

以下のコードで発生。

fun main() {

    var i:Int = 10
    
    if (i => 1) {
        println(i)        
    }

}

エラーメッセージ

test.kt:5:10: error: expecting ')
    if (i => 1) {
         ^
test.kt:5:11: error: expecting an expression
    if (i => 1) {
          ^
test.kt:5:11: error: unexpected tokens (use ';' to separate expressions on the same line)
    if (i => 1) {
          ^
test.kt:5:9: error: type mismatch: inferred type is Int but Boolean was expected
    if (i => 1) {

原因

比較演算子の記述間違い

対処法

以下を条件にするなら「<=」を使用し、以上を条件にするなら「>=」を使用する

fun main() {

    var i:Int = 10

    if (i >= 1) {
        println(i)        
    }

}