This page is no longer maintained — Please continue to the home page at www.scala-lang.org

accessing variables in higher scope

2 replies
northfuse
Joined: 2011-06-10,
User offline. Last seen 1 year 18 weeks ago.

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!

Aaron Novstrup 2
Joined: 2011-03-30,
User offline. Last seen 42 years 45 weeks ago.
Re: accessing variables in higher scope

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!

Lex
Joined: 2010-02-28,
User offline. Last seen 42 years 45 weeks ago.
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.

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland