Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
demo C# and Scala's lazy val and lambda capturing
$ csc test.cs
Microsoft (R) Visual C# Compiler version 2.0.0.61404
Copyright (C) Microsoft Corporation. All rights reserved.
$ mono test.exe eager
MainThread
$ mono test.exe
NewTestThread
$ scalac test.scala
$ java -cp $SCALA_HOME/lib/*:. TestLazy eager
main
$ java -cp $SCALA_HOME/lib/*:. TestLazy
Thread-0
using System;
using System.Threading;
using System.Linq;
class TestLazy {
Lazy<string> Name = new Lazy<string>(() => Thread.CurrentThread.Name);
static void Main(string[] args) {
Thread.CurrentThread.Name = "MainThread";
var test = new TestLazy();
if (args.FirstOrDefault() == "eager") {
// force evaluation of the lazy val
var dummy = test.Name.Value;
}
var thread = new Thread(() => Console.WriteLine(test.Name.Value));
thread.Name = "NewTestThread";
thread.Start();
thread.Join();
}
}
object TestLazy {
def main(args: Array[String]) = {
val test = new TestLazy()
args.headOption match {
case Some("eager") => test.name
case _ =>
}
val thread = new Thread {
override def run() = println(test.name)
}
thread.start
thread.join
}
}
class TestLazy {
lazy val name = Thread.currentThread.getName
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment