Lambdas in Visual Basic
Function() and Sub() expressions, one line or a full block.
Dim twice = Function(n As Integer) n * 2
Console.WriteLine(twice(21))
Dim shout As Action(Of String) = Sub(s) Console.WriteLine(s.ToUpper())
shout("done")
Dim describe = Function(n As Integer)
If n Mod 2 = 0 Then Return $"{n} is even"
Return $"{n} is odd"
End Function
For Each n In {7, 12}
Console.WriteLine(describe(n))
Next
How it works
Function(n As Integer) n * 2returns its expression.- A
Sublambda fits anActionslot — statements, no value. - Multi-line lambdas open a block and close with
End Function.
Keywords and builtins used here
DimEachEndForFunctionIfIntegerNextOfReturnStringThen
The run, in numbers
- Lines
- 14
- Characters to type
- 329
- Tokens
- 97
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 73 seconds.
Step 3 of 3 in Subs & functions, step 15 of 29 in Language basics.