Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Allow lazy val in class parameter. #5244

Closed
scabug opened this issue Nov 29, 2011 · 1 comment
Closed

Feature request: Allow lazy val in class parameter. #5244

scabug opened this issue Nov 29, 2011 · 1 comment

Comments

@scabug
Copy link

scabug commented Nov 29, 2011

Currently, this is not allowed:

class Foo(lazy val p: String)

Although I can create another lazy val like this:

class Foo(p: => String) {
  lazy val p2 = p
}

But it wastes memory since it creates three fields in byte codes:

public class Foo implements scala.ScalaObject {
  private final scala.Function0<java.lang.String> p;
  private java.lang.String p2;
  public volatile int bitmap$0;
  public java.lang.String p2();
  public Foo(scala.Function0<java.lang.String>);
}

I suggest that scalac automatically generate code for class Foo(lazy val p: String) like this:

object Foo {
	private final def createLazy(setter: Function0[String] => Unit,
			initial: => String) = { () =>
		val result = initial
		setter { () => result }
		result
	}
}

class Foo(p: => String) {
	var p2: Function0[String] = FasterLazy(p2_=, p)
}

This approach creates only one field:

public class Foo implements scala.ScalaObject {
  private scala.Function0<java.lang.String> p2;
  public scala.Function0<java.lang.String> p2();
  public void p2_$eq(scala.Function0<java.lang.String>);
  public Foo(scala.Function0<java.lang.String>);
}

And it even a little faster than lazy val, since it omits checking if the field initialized or not.

@scabug
Copy link
Author

scabug commented Nov 29, 2011

Imported From: https://issues.scala-lang.org/browse/SI-5244?orig=1
Reporter: @Atry
Affected Versions: 2.9.1
Duplicates #240

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant