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

For loops with result types, you must ensure that:

  • All break statements provide an argument of the correct type

  • The else branch (if present) returns a value of the correct type

错误示例#

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:

  • Add an argument to the break statement that matches the loop's result type. For example,

pub fn g(x: Int) -> Int {
  for i in 0..=x {
    if i == 42 {
      break i
    }
  } else {
    0
  }
}
  • Remove the else branch if you don't need to return a value from the loop.

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