- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
accessing variables in higher scope
Fri, 2011-06-10, 23:46
I'm trying to use a variable in a different scope (within a trait
creation) but can't figure out how to do it. Here's an example:
def foo(hours : Int) = new FooWrapper {
val hours = hours
}
I want the FooWrapper trait which has a val hours to use the hours
parameter from the method foo.
I have been doing it this way but hope there is a better way:
def foo(hours : Int) = {
val myhours = hours
new FooWrapper {
val hours = myhours
}
}
Thanks!
Sat, 2011-06-11, 04:07
#2
Re: accessing variables in higher scope
You are doing it correctly, using a local variable with a different
name is the way to go.
Antonymous classes do not always incur a reflection overhead. If
FooWrapper has "val hours" declared, then there will be no reflection
overhead. On the other hand if you declare AND use outside the
anonymous class some values or methods not defined in the supertypes,
then reflection will be used.
On Fri, Jun 10, 2011 at 6:56 PM, Aaron Novstrup
wrote:
> This isn't a direct answer, but the best solution would be to define a class:
>
> def foo(hours: Int) = new FooWrapperImpl(hours)
> class FooWrapperImpl(val hours) extends FooWrapper
>
> Anonymous classes incur runtime (reflection) overhead in Scala,
> because they are implemented as structural types.
This isn't a direct answer, but the best solution would be to define a class:
def foo(hours: Int) = new FooWrapperImpl(hours)
class FooWrapperImpl(val hours) extends FooWrapper
Anonymous classes incur runtime (reflection) overhead in Scala,
because they are implemented as structural types.
On Fri, Jun 10, 2011 at 3:38 PM, Tyler Southwick
wrote:
> I'm trying to use a variable in a different scope (within a trait
> creation) but can't figure out how to do it. Here's an example:
>
> def foo(hours : Int) = new FooWrapper {
> val hours = hours
> }
>
> I want the FooWrapper trait which has a val hours to use the hours
> parameter from the method foo.
>
> I have been doing it this way but hope there is a better way:
>
> def foo(hours : Int) = {
> val myhours = hours
> new FooWrapper {
> val hours = myhours
> }
> }
>
> Thanks!