mixins: problem with variables?
Posted: Fri Nov 11, 2011 3:12 pm
Hi,
I have started to look at mixins. What I am aiming to do is add some implemented methods and perhaps state to a couple of otherwise independent classes. I've hit a problem, which suggests it is not possible to define local variables in a method defined in a mixin. For example:
I create one file 'main.cobra' with the code:
and then a file 'mixin.cobra' with the code:
$ cobra mixin.cobra main.cobra
and everything is fine. (Although I went on a little detour in my current project, before realising the order of the files was significant...)
But if I modify the file 'mixin.cobra' to:
Then I get errors on compiling:
$ cobra mixin.cobra main.cobra
main.cobra(3): error: The name "myvar" does not exist in the current context
main.cobra(4): error: The name "myvar" does not exist in the current context
Compilation failed - 2 errors, 0 warnings
Not running due to errors above.
(It is also a little confusing that the errors refer to the file holding the class which adds the mixin.)
Given the above, I've changed my program to use instance variables, but I noticed that a variable defined in a 'using' block, e.g.:
throws a warning:
> warning: The value of variable "document" is never used.
but the program works.
I have started to look at mixins. What I am aiming to do is add some implemented methods and perhaps state to a couple of otherwise independent classes. I've hit a problem, which suggests it is not possible to define local variables in a method defined in a mixin. For example:
I create one file 'main.cobra' with the code:
class TestMixin adds MyCode
def main
print "from main"
.hi
and then a file 'mixin.cobra' with the code:
mixin MyCode
def hi
print "hi"
$ cobra mixin.cobra main.cobra
and everything is fine. (Although I went on a little detour in my current project, before realising the order of the files was significant...)
But if I modify the file 'mixin.cobra' to:
mixin MyCode
def hi
myvar = 0
print "hi [myvar]"
Then I get errors on compiling:
$ cobra mixin.cobra main.cobra
main.cobra(3): error: The name "myvar" does not exist in the current context
main.cobra(4): error: The name "myvar" does not exist in the current context
Compilation failed - 2 errors, 0 warnings
Not running due to errors above.
(It is also a little confusing that the errors refer to the file holding the class which adds the mixin.)
Given the above, I've changed my program to use instance variables, but I noticed that a variable defined in a 'using' block, e.g.:
def savePdfAnalysis(filename as String, index as int)
using document = Document()
PdfWriter.getInstance(document, File.create(filename))
document.open
document.add(Paragraph("Analysis of document pair [index]"))
throws a warning:
> warning: The value of variable "document" is never used.
but the program works.