Declaration of a Class inside a Function


If I try and do

fun Test ()

  public class OpOver (theInt : Int) {
  var value : Int = theInt;
  fun inc() : OpOver
           value = value + 1;
           return this;
  fun toString() : String
           return Integer.toString(value)

  var someVar = OpOver(10);
  println(“The value is : {someVar}")   someVar++;   println("The value after increment is : {someVar}”)


I get a compile error on the “fun inc() : OpOver” line:

Error (xx,xx) Kotlin: Unresolved reference: OpOver

The IDE also highlights OpOver in red (tool tip says: Unresolved reference: OpOver).

If I move the class declaration above/outside the function declaration, then it compiles and runs.

Or, if I remove the inc() function and the ++ operation, it compiles and runs with the class definition inside the function.

Just wondering why I am getting this behavior.


Your code is valid and "Unresolved reference" in this case is a bug in Kotlin M6.2 compiler. An issue can be found in our tracker (KT-4351), and it has been fixed recently. So you can either use non-local class until the next release or update to some nightly build. Please proceed to Using a pre-built Kotlin IDEA plugin to know how to install more recent but not-yet-realeased Kotlin if you're ready to choose the second option.