Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active April 2, 2023 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/06123560e26aebc83cbc91d4f952002d to your computer and use it in GitHub Desktop.
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/7f55d6f4b42e8498a091dddc0e2e205f843ae2f1
// 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 NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// 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.1.1"
// ---------------------
// ----------------------------------------------------------------
// 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