Skip to content

Instantly share code, notes, and snippets.

@rednaxelafx
Last active April 10, 2018 07:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rednaxelafx/32574a3db9e46b09ddf4218e3185f3a8 to your computer and use it in GitHub Desktop.
Save rednaxelafx/32574a3db9e46b09ddf4218e3185f3a8 to your computer and use it in GitHub Desktop.
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