- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Question about var constructor arguments
Mon, 2009-03-23, 14:54
Let's say I have:
class MyClass(var text : String)
{
}
val x = new MyClass("apple")
val y = new MyClass("orange")
x.text = "pear"
Is it possible to override text_=(x : String) in such a way that apart from
setting the value of file text I can achieve some side effect.
The only thing I can think of is have a val parameter with a different name
in the constructor, a private var that initially holds a copy of that
initial value and separate "text : String" and "text_=(x : String)" methods.
Can this be done in a more direct way?
Thanks,
Silvio
Mon, 2009-03-23, 15:27
#2
Re: Question about var constructor arguments
Excellent, simple and elegant! Why didn't I think of that?
Silvio
Erik Engbrecht wrote:
>
> class MyClass(private var _text: String) {
> def text = _text
> def text_=(v: String): Unit = { _test = v; // some effect }
> }
>
> the var is private but the constructor is still public.
>
> On Mon, Mar 23, 2009 at 9:53 AM, Silvio Bierman
> > wrote:
>
>>
>> Let's say I have:
>>
>> class MyClass(var text : String)
>> {
>> }
>>
>> val x = new MyClass("apple")
>> val y = new MyClass("orange")
>>
>> x.text = "pear"
>>
>> Is it possible to override text_=(x : String) in such a way that apart
>> from
>> setting the value of file text I can achieve some side effect.
>>
>> The only thing I can think of is have a val parameter with a different
>> name
>> in the constructor, a private var that initially holds a copy of that
>> initial value and separate "text : String" and "text_=(x : String)"
>> methods.
>>
>> Can this be done in a more direct way?
>>
>> Thanks,
>>
>> Silvio
>>
>> --
>> View this message in context:
>> http://www.nabble.com/Question-about-var-constructor-arguments-tp2266059...
>> Sent from the Scala - User mailing list archive at Nabble.com.
>>
>>
>
>
def text = _text
def text_=(v: String): Unit = { _test = v; // some effect }
}
the var is private but the constructor is still public.
On Mon, Mar 23, 2009 at 9:53 AM, Silvio Bierman <sbierman@jambo-software.com> wrote:
--
http://erikengbrecht.blogspot.com/