Last active
February 3, 2026 20:25
-
-
Save dacr/06123560e26aebc83cbc91d4f952002d to your computer and use it in GitHub Desktop.
instantiate automatically a trait or an abstract using a lambda / published by https://github.com/dacr/code-examples-manager #0e3cf69d-15ce-4053-8221-029f97d7de2d/70d8f41497cd3e30ee02484fef122477854d920b
This file contains hidden or 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
| // summary : instantiate automatically a trait or an abstract using a lambda | |
| // keywords : scala, language-feature, lambda, autoinstantiate, @testable | |
| // publish : gist | |
| // authors : David Crosson | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // id : 0e3cf69d-15ce-4053-8221-029f97d7de2d | |
| // created-on : 2021-07-06T18:27:07+02:00 | |
| // managed-by : https://github.com/dacr/code-examples-manager | |
| // execution : scala ammonite script (http://ammonite.io/) - run as follow 'amm scriptname.sc' | |
| // run-with : scala-cli $file | |
| // --------------------- | |
| //> using scala "3.4.2" | |
| // --------------------- | |
| // ---------------------------------------------------------------- | |
| // works with trait | |
| trait Truc { | |
| def machin(x:String):Int | |
| } | |
| val truc:Truc = x => x.toInt | |
| println(truc.machin("42")) | |
| // ---------------------------------------------------------------- | |
| // also works with abstract class, in all case if and only if there's just one undefined function | |
| abstract class Bidule{ | |
| def blah(x:String):Int = 42 | |
| def bouh(x:Int, y:Int):Int | |
| } | |
| val bidule: Bidule = (x, y) => x + y | |
| println(bidule.bouh(40, 2)) | |
| // ---------------------------------------------------------------- | |
| println("Thanks to RockTheJVM for this nice scala trick") | |
| println("https://www.youtube.com/watch?v=aX-Lc6NXhC8&ab_channel=RocktheJVM") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment