Skip to main content
April 27, 2010
Question

Implicit getters/setters and interfaces

  • April 27, 2010
  • 2 replies
  • 3050 views

What's the best way around this problem with interfaces?

public interface ITest {

     function set testField(test:String):void;

}

public class Test implements ITest {

     public var testField;

}

This complains I didn't implement the interface - bull! 

Test does have a setter for testField (an implicit one).  I don't want to define an explicit one for every single field I have defined in my interface.  There doesn't seem to be a way to define getters/setters in interfaces (or the syntax just escapes me).

Do I have to do this explicit getter/setter nonsense in order to use interfaces in this way?  I'd rather not throw away this rather awesome feature of AS3 so I hope there's some easy workaround...

After asking The Google and some search (attempts) here I couldn't find anything on this, so perhaps I'm missing something obvious.  It's early in the morning...

This topic has been closed for replies.

2 replies

April 27, 2010

You can define getters and setters in an interface just fine. What is wrong is that you have testField defined as a variable... it's not a variable it's a function. Get rid of the variable declaration, change to a public function and you should be fine.

April 27, 2010

Nothing wrong with the interface declaration. But the implementation is wrong - testField needs to be a public function matching the signature declared in the interface.

public interface ITest {

     function set testField(test:String):void;
}



public class Test implements ITest {

     var _testField:String;

     public function set testField(test:String):void

     {

          _testField= test;

     }

}

April 27, 2010

This is my problem - I want the getter/setter to be implicit in the class, I don't want to do all this:

public class Test implements ITest {


     var _testField:String;

     public function set testField(test:String):void

     {

          _testField= test;

     }

}

I know this fixes the problem but again it's throwing away an advantage of an implicit getter/setter.  (Not having to create that whole function, not to mention I can't stand underscore conventions. )


So there's really no way to avoid the function or to "declare a field" in an interface, I assume?

April 27, 2010

The only workaround, it seems, is to drop interfaces entirely and simply define the fields in a base class.  Probably not the best solution but I suppose there's little choice unless someone else knows otherwise.  I'm surprised there aren't others wondering what gives about this AS3 interface annoyance.

public class BaseTest {

     var testField:String;

}

public class Test extends BaseTest {

}