Duplicate method error


#1

I wrote a simple Kotlin program following:

class Foo() {

  private var foo: Int = 0

  fun getFoo(): Int {
  return foo
  }

}

val f: Foo = Foo()


This code was compiled without any error, but I got a runtime error:

Exception in thread "main" java.lang.ClassFormatError: Duplicate method name&signature in class file main/Foo

I guess this is because the compiler implicitly creates getFoo() and setFoo(). Is this a bug? Are there any way to avoid this error?

I know accessors declaration is not recommended, but I want to write getters and setters to keep consistency with Java.


#2

Hi Ziphil!

The methods “getFoo” and “setFoo” for property are generated exactly for java interop. So you write only

class Foo() {
  var foo: Int = 0
}

in Kotlin and you use it as

``


from Java.

If you want your custom getters and setters (not just return value and set value) you use the following syntax:

var foo: Int = 0   get() = $foo   private set(value: Int) {   doSomethingSpecial()   $foo = value   }

There is a very old request to forbig declaring functions with the same JVM signature (KT-1).
I’ve created another one specifically for your case (KT-4287).