E4105

E4105#

Current loop has result type mismatch with break argument.

This error occurs when the type of the argument provided to a break statement does not match the expected result type of the loop. In MoonBit, loops can have result types, and when using break with an argument, that argument’s type must match the loop’s result type. When an argument is not provided, the loop’s result type must be Unit.

This mismatch can happen in two ways:

  1. The loop expects a value of a certain type, but break is called with no argument

  2. The loop expects a value of type A, but break is called with an argument of type B

对于具有结果类型的循环,您必须确保:

  • 所有 break 语句都提供正确类型的参数

  • else 分支(如果存在)返回正确类型的值

错误示例#

pub fn g(x: Int) -> Int {
  for i in 0..=x {
    if i == 42 {
      break
//    ^^^^^ Error: Current loop has result type Int, but `break` is supplied
//                 with no arguments.
    }
  } else {
    0
  }
}

建议#

To fix this error, you can:

  • break 语句添加一个与循环结果类型匹配的参数。例如,

pub fn g(x: Int) -> Int {
  for i in 0..=x {
    if i == 42 {
      break i
    }
  } else {
    0
  }
}
  • 如果不需要从循环中返回值,请删除 else 分支。

pub fn g(x: Int) -> Unit {
  for i in 0..=x {
    if i == 42 {
      break
    }
  }
}