Last active
April 10, 2018 07:09
-
-
Save rednaxelafx/32574a3db9e46b09ddf4218e3185f3a8 to your computer and use it in GitHub Desktop.
demo C# and Scala's lazy val and lambda capturing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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