stevan / p5-mop-redux

A(nother) MOP for Perl 5
139 stars 36 forks source link

Do we have to say is? #79

Closed oylenshpeegul closed 10 years ago

oylenshpeegul commented 10 years ago

When I run this code

#!/usr/bin/env perl

use v5.18;
use warnings;
use mop;

class myBaseClass {
    has $!myID;
    has $!myName;
    method doMsg ($m) { say $m }
}

class myDerivedClass extends myBaseClass {
    method hello { say __LINE__." Hello from myDerivedClass" }
}

my $v= myDerivedClass->new(myID => time , myName => 'DC');
$v->hello;
$v->doMsg($v->myName ." Very nice! How much RAM is Eclipse using?");

I get an error

$ ./usemop.pl
14 Hello from myDerivedClass
Could not find myName in myDerivedClass=SCALAR(0x1b1bc48) at /home/tim/.plenv/versions/5.18.1/lib/perl5/site_perl/5.18.1/mop/internals/mro.pm line 141.

But if I change line 9 to

    has $!myName is ro;

it works as expected

$ ./usemop.pl
14 Hello from myDerivedClass
DC Very nice! How much RAM is Eclipse using?
stevan commented 10 years ago

Yes, no accessors will be created unless you ask for them to be created.

oylenshpeegul commented 10 years ago

I see. Thanks!

I guess I read here

http://blogs.perl.org/users/damien_dams_krotkine/2013/09/p5-mop.html

that you can add is, but it's really that you must.

stevan commented 10 years ago

Well, you don't need to generate an accessor if you are accessing the attribute in the class in which it is defined. For that you can simply access the variable directly, like so:

class Foo {
    has $!bar;
    method bar { $!bar }
}

But since they attributes are private the class in which they were defined, you cannot access it the same way in a subclass. This is where you would create an accessor (which yes, requires you to use the is modifier and the ro or rw trait).

oylenshpeegul commented 10 years ago

Ah. Thanks again!

stevan commented 10 years ago

Closing this as it seems the question has been answered and this is resolved.