람다 식(Visual Basic)

람다 식은 대리자가 유효한 곳마다 사용할 수 있는 이름이 없는 함수 또는 서브루틴입니다. 람다 식은 함수 또는 서브루틴일 수 있으며 한 줄 또는 여러 줄일 수 있습니다. 현재 범위의 값을 람다 식으로 전달할 수 있습니다.

참고 항목

RemoveHandler 문은 예외입니다. RemoveHandler 대리자 매개 변수에 대해 람다 식을 전달할 수 없습니다.

표준 함수 또는 서브루틴을 만드는 것처럼 Function 또는 Sub 키워드를 사용하여 람다 식을 만듭니다. 그러나 람다 식은 문에 포함됩니다.

다음 예제는 인수를 증가시키고 값을 반환하는 람다 식입니다. 이 예제에서는 함수에 대한 한 줄과 여러 줄로 된 람다 식 구문을 모두 보여 줍니다.

Dim increment1 = Function(x) x + 1
Dim increment2 = Function(x)
                     Return x + 2
                 End Function

' Write the value 2.
Console.WriteLine(increment1(1))

' Write the value 4.
Console.WriteLine(increment2(2))

다음 예제는 콘솔에 값을 쓰는 람다 식입니다. 이 예제에서는 서브루틴에 대한 한 줄 및 여러 줄 람다 식 구문을 모두 보여 줍니다.

Dim writeline1 = Sub(x) Console.WriteLine(x)
Dim writeline2 = Sub(x)
                     Console.WriteLine(x)
                 End Sub

' Write "Hello".
writeline1("Hello")

' Write "World"
writeline2("World")

이전 예제에서 람다 식은 변수 이름에 할당됩니다. 변수를 참조할 때마다 람다 식을 호출합니다. 다음 예제와 같이 람다 식을 동시에 선언하고 호출할 수도 있습니다.

Console.WriteLine((Function(num As Integer) num + 1)(5))

람다 식은 다음 예제와 같이 함수 호출의 값으로 반환되거나(이 항목의 뒷부분에 있는 Context 섹션의 예제와 같이) 대리자 형식을 사용하는 매개 변수에 인수로 전달될 수 있습니다.

Module Module2

    Sub Main()
        ' The following line will print Success, because 4 is even.
        testResult(4, Function(num) num Mod 2 = 0)
        ' The following line will print Failure, because 5 is not > 10.
        testResult(5, Function(num) num > 10)
    End Sub

    ' Sub testResult takes two arguments, an integer value and a 
    ' delegate function that takes an integer as input and returns
    ' a boolean. 
    ' If the function returns True for the integer argument, Success
    ' is displayed.
    ' If the function returns False for the integer argument, Failure
    ' is displayed.
    Sub testResult(ByVal value As Integer, ByVal fun As Func(Of Integer, Boolean))
        If fun(value) Then
            Console.WriteLine("Success")
        Else
            Console.WriteLine("Failure")
        End If
    End Sub

End Module

람다 식 구문

람다 식의 구문은 표준 함수 또는 서브루틴의 구문과 유사합니다. 차이점은 다음과 같습니다.

  • 람다 식에는 이름이 없습니다.

  • 람다 식에는 Overloads 또는 Overrides 같은 한정자를 사용할 수 없습니다.

  • 한 줄 람다 함수는 As 절을 사용하여 반환 형식을 지정하지 않습니다. 대신 형식은 람다 식의 본문이 계산하는 값에서 유추됩니다. 예를 들어 람다 식의 본문이 cust.City = "London"인 경우 반환 형식은 Boolean입니다.

  • 여러 줄 람다 함수에서 As 절을 사용하여 반환 형식을 지정하거나 반환 형식이 유추되도록 As 절을 생략할 수 있습니다. 여러 줄 람다 함수에 대해 As 절을 생략하면 반환 형식이 여러 줄 람다 함수의 모든 Return 문에서 지배적 형식으로 유추됩니다. 주요 형식은 다른 모든 형식으로 확장할 수 있는 고유한 형식입니다. 이 고유 형식을 확인할 수 없는 경우 주 형식은 배열의 다른 모든 형식이 좁힐 수 있는 고유 형식입니다. 이러한 고유 형식을 모두 확인할 수 없는 경우 기준 형식은 Object입니다. 이 경우 Option StrictOn로 설정되면 컴파일러 오류가 발생합니다.

    예를 들어 Return 문에 제공된 식에 Integer, LongDouble 형식의 값이 포함된 경우 결과 배열은 Double 형식입니다. IntegerLong는 모두 Double으로 확대되고 Double만 해당됩니다. 따라서 기준 형식은 Double 입니다. 자세한 내용은 Widening and Narrowing Conversions을 참조하세요.

  • 한 줄 함수의 본문은 문이 아닌 값을 반환하는 식이어야 합니다. 한 줄 함수에 대한 Return 문이 없습니다. 한 줄 함수에서 반환되는 값은 함수 본문에 있는 식의 값입니다.

  • 한 줄 서브루틴의 본문은 한 줄 문이어야 합니다.

  • 한 줄 함수 및 서브루틴에는 End Function 또는 End Sub 문이 포함되지 않습니다.

  • As 키워드를 사용하여 람다 식 매개 변수의 데이터 형식을 지정하거나 매개 변수의 데이터 형식을 유추할 수 있습니다. 모든 매개 변수에는 지정된 데이터 형식이 있거나 모두 유추되어야 합니다.

  • OptionalParamarray 매개 변수는 허용되지 않습니다.

  • 제네릭 매개 변수는 허용되지 않습니다.

비동기 람다

AsyncAwait 연산자 키워드를 사용하여 비동기 처리를 통합하는 람다 식과 문을 쉽게 만들 수 있습니다. 예를 들어 다음 Windows Forms 예제에는 비동기 메서드 ExampleMethodAsync를 호출하고 기다리는 이벤트 처리기가 포함되어 있습니다.

Public Class Form1

    Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' ExampleMethodAsync returns a Task.
        Await ExampleMethodAsync()
        TextBox1.Text = vbCrLf & "Control returned to button1_Click."
    End Sub

    Async Function ExampleMethodAsync() As Task
        ' The following line simulates a task-returning asynchronous process.
        Await Task.Delay(1000)
    End Function

End Class

AddHandler 문에서 비동기 람다를 사용하여 동일한 이벤트 처리기를 추가할 수 있습니다. 이 처리기를 추가하려면 다음 예제에 표시된 것처럼 람다 매개 변수 목록에 Async 한정자를 추가합니다.

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        AddHandler Button1.Click,
            Async Sub(sender1, e1)
                ' ExampleMethodAsync returns a Task.
                Await ExampleMethodAsync()
                TextBox1.Text = vbCrLf & "Control returned to Button1_ Click."
            End Sub
    End Sub

    Async Function ExampleMethodAsync() As Task
        ' The following line simulates a task-returning asynchronous process.
        Await Task.Delay(1000)
    End Function

End Class

비동기 메서드를 만들고 사용하는 방법에 대한 자세한 내용은 Async 및 Await를 사용한 비동기 프로그래밍을 참조하세요.

Context

람다 식은 정의된 범위와 컨텍스트를 공유합니다. 포함된 범위에 기록된 모든 코드와 동일한 액세스 권한을 가짐 여기에는 포함하는 범위의 멤버 변수, 함수 및 하위, Me 및 매개 변수 및 지역 변수에 대한 액세스가 포함됩니다.

포함하는 범위의 지역 변수 및 매개 변수에 대한 액세스는 해당 범위의 수명을 초과하여 확장할 수 있습니다. 가비지 수집에 람다 식을 참조하는 대리자를 사용할 수 없는 한 원래 환경의 변수에 대한 액세스는 유지됩니다. 다음 예제에서 변수 target은 람다 식 playTheGame이 정의된 메서드인 makeTheGame에 대해 로컬입니다. MaintakeAGuess로 할당된 반환된 람다 식은 여전히 지역 변수 target에 액세스할 수 있습니다.

Module Module6

    Sub Main()
        ' Variable takeAGuess is a Boolean function. It stores the target
        ' number that is set in makeTheGame.
        Dim takeAGuess As gameDelegate = makeTheGame()

        ' Set up the loop to play the game.
        Dim guess As Integer
        Dim gameOver = False
        While Not gameOver
            guess = CInt(InputBox("Enter a number between 1 and 10 (0 to quit)", "Guessing Game", "0"))
            ' A guess of 0 means you want to give up.
            If guess = 0 Then
                gameOver = True
            Else
                ' Tests your guess and announces whether you are correct. Method takeAGuess
                ' is called multiple times with different guesses. The target value is not 
                ' accessible from Main and is not passed in.
                gameOver = takeAGuess(guess)
                Console.WriteLine("Guess of " & guess & " is " & gameOver)
            End If
        End While

    End Sub

    Delegate Function gameDelegate(ByVal aGuess As Integer) As Boolean

    Public Function makeTheGame() As gameDelegate

        ' Generate the target number, between 1 and 10. Notice that 
        ' target is a local variable. After you return from makeTheGame,
        ' it is not directly accessible.
        Randomize()
        Dim target As Integer = CInt(Int(10 * Rnd() + 1))

        ' Print the answer if you want to be sure the game is not cheating
        ' by changing the target at each guess.
        Console.WriteLine("(Peeking at the answer) The target is " & target)

        ' The game is returned as a lambda expression. The lambda expression
        ' carries with it the environment in which it was created. This 
        ' environment includes the target number. Note that only the current
        ' guess is a parameter to the returned lambda expression, not the target. 

        ' Does the guess equal the target?
        Dim playTheGame = Function(guess As Integer) guess = target

        Return playTheGame

    End Function

End Module

다음 예제에서는 중첩된 람다 식의 광범위한 액세스 권한을 보여 줍니다. 반환된 람다 식이 Main에서 aDel로 실행되면 다음 요소에 액세스합니다.

  • 정의된 클래스의 필드입니다. aField

  • 정의된 클래스의 속성입니다. aProp

  • 정의된 메서드 functionWithNestedLambda의 매개 변수입니다. level1

  • functionWithNestedLambda의 지역 변수: localVar

  • 중첩된 람다 식의 매개 변수입니다. level2

Module Module3

    Sub Main()
        ' Create an instance of the class, with 1 as the value of 
        ' the property.
        Dim lambdaScopeDemoInstance =
            New LambdaScopeDemoClass With {.Prop = 1}

        ' Variable aDel will be bound to the nested lambda expression  
        ' returned by the call to functionWithNestedLambda.
        ' The value 2 is sent in for parameter level1.
        Dim aDel As aDelegate =
            lambdaScopeDemoInstance.functionWithNestedLambda(2)

        ' Now the returned lambda expression is called, with 4 as the 
        ' value of parameter level3.
        Console.WriteLine("First value returned by aDel:   " & aDel(4))

        ' Change a few values to verify that the lambda expression has 
        ' access to the variables, not just their original values.
        lambdaScopeDemoInstance.aField = 20
        lambdaScopeDemoInstance.Prop = 30
        Console.WriteLine("Second value returned by aDel: " & aDel(40))
    End Sub

    Delegate Function aDelegate(
        ByVal delParameter As Integer) As Integer

    Public Class LambdaScopeDemoClass
        Public aField As Integer = 6
        Dim aProp As Integer

        Property Prop() As Integer
            Get
                Return aProp
            End Get
            Set(ByVal value As Integer)
                aProp = value
            End Set
        End Property

        Public Function functionWithNestedLambda(
            ByVal level1 As Integer) As aDelegate

            Dim localVar As Integer = 5

            ' When the nested lambda expression is executed the first 
            ' time, as aDel from Main, the variables have these values:
            ' level1 = 2
            ' level2 = 3, after aLambda is called in the Return statement
            ' level3 = 4, after aDel is called in Main
            ' localVar = 5
            ' aField = 6
            ' aProp = 1
            ' The second time it is executed, two values have changed:
            ' aField = 20
            ' aProp = 30
            ' level3 = 40
            Dim aLambda = Function(level2 As Integer) _
                              Function(level3 As Integer) _
                                  level1 + level2 + level3 + localVar +
                                    aField + aProp

            ' The function returns the nested lambda, with 3 as the 
            ' value of parameter level2.
            Return aLambda(3)
        End Function

    End Class
End Module

대리자 형식으로 변환

람다 식은 호환되는 대리자 형식으로 암시적으로 변환될 수 있습니다. 호환성에 대한 일반적인 요구 사항에 대한 자세한 내용은 완화된 대리자 변환을 참조하세요. 예를 들어 다음 코드 예제에서는 암시적으로 Func(Of Integer, Boolean)로 변환하는 람다 식 또는 일치하는 대리자 서명을 보여 줍니다.

' Explicitly specify a delegate type.
Delegate Function MultipleOfTen(ByVal num As Integer) As Boolean

' This function matches the delegate type.
Function IsMultipleOfTen(ByVal num As Integer) As Boolean
    Return num Mod 10 = 0
End Function

' This method takes an input parameter of the delegate type. 
' The checkDelegate parameter could also be of 
' type Func(Of Integer, Boolean).
Sub CheckForMultipleOfTen(ByVal values As Integer(),
                          ByRef checkDelegate As MultipleOfTen)
    For Each value In values
        If checkDelegate(value) Then
            Console.WriteLine(value & " is a multiple of ten.")
        Else
            Console.WriteLine(value & " is not a multiple of ten.")
        End If
    Next
End Sub

' This method shows both an explicitly defined delegate and a
' lambda expression passed to the same input parameter.
Sub CheckValues()
    Dim values = {5, 10, 11, 20, 40, 30, 100, 3}
    CheckForMultipleOfTen(values, AddressOf IsMultipleOfTen)
    CheckForMultipleOfTen(values, Function(num) num Mod 10 = 0)
End Sub

다음 코드 예제에서는 암시적으로 Sub(Of Double, String, Double)로 변환하는 람다 식 또는 일치하는 대리자 서명을 보여 줍니다.

Module Module1
    Delegate Sub StoreCalculation(ByVal value As Double,
                                  ByVal calcType As String,
                                  ByVal result As Double)

    Sub Main()
        ' Create a DataTable to store the data.
        Dim valuesTable = New DataTable("Calculations")
        valuesTable.Columns.Add("Value", GetType(Double))
        valuesTable.Columns.Add("Calculation", GetType(String))
        valuesTable.Columns.Add("Result", GetType(Double))

        ' Define a lambda subroutine to write to the DataTable.
        Dim writeToValuesTable = Sub(value As Double, calcType As String, result As Double)
                                     Dim row = valuesTable.NewRow()
                                     row(0) = value
                                     row(1) = calcType
                                     row(2) = result
                                     valuesTable.Rows.Add(row)
                                 End Sub

        ' Define the source values.
        Dim s = {1, 2, 3, 4, 5, 6, 7, 8, 9}

        ' Perform the calculations.
        Array.ForEach(s, Sub(c) CalculateSquare(c, writeToValuesTable))
        Array.ForEach(s, Sub(c) CalculateSquareRoot(c, writeToValuesTable))

        ' Display the data.
        Console.WriteLine("Value" & vbTab & "Calculation" & vbTab & "Result")
        For Each row As DataRow In valuesTable.Rows
            Console.WriteLine(row(0).ToString() & vbTab &
                              row(1).ToString() & vbTab &
                              row(2).ToString())
        Next

    End Sub


    Sub CalculateSquare(ByVal number As Double, ByVal writeTo As StoreCalculation)
        writeTo(number, "Square     ", number ^ 2)
    End Sub

    Sub CalculateSquareRoot(ByVal number As Double, ByVal writeTo As StoreCalculation)
        writeTo(number, "Square Root", Math.Sqrt(number))
    End Sub
End Module

람다 식을 대리자로 할당하거나 프로시저에 인수로 전달하는 경우 매개 변수 이름을 지정하지만 해당 데이터 형식을 생략하여 형식을 대리자에서 제거할 수 있습니다.

예제

  • 다음 예제에서는 nullable 값 형식 인수에 할당된 값이 있는 경우 True을 반환하고 해당 값이 Nothing인 경우 False를 반환하는 람다 식을 정의합니다.

    Dim notNothing =
      Function(num? As Integer) num IsNot Nothing
    Dim arg As Integer = 14
    Console.WriteLine("Does the argument have an assigned value?")
    Console.WriteLine(notNothing(arg))
    
  • 다음 예제에서는 배열에서 마지막 요소의 인덱스를 반환하는 람다 식을 정의합니다.

    Dim numbers() = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    Dim lastIndex =
      Function(intArray() As Integer) intArray.Length - 1
    For i = 0 To lastIndex(numbers)
        numbers(i) += 1
    Next
    

참고 항목