Kotlin中函数调用赋值给变量时是否会立即执行该函数?
Great question! Let’s break this down with your exact example to make it crystal clear.
First, let’s clarify the core behavior:
When you write val userData = GraphRequest.newMeRequest(...), the newMeRequest() function is called immediately at the moment that line of code runs. But here’s the key detail: it doesn’t actually send the Graph API request yet.
What’s happening under the hood:
newMeRequest is a factory method—its job is to create and return a configured GraphRequest object. This object holds all the details you’ve provided:
- The
accessTokenfor authentication - Your
GraphJSONObjectCallbackthat defines what to do when the request completes
So userData isn’t storing the result of the request, and it isn’t storing the function itself—it’s storing the pre-configured request object that’s ready to be executed.
When does the actual request run?
The callback onCompleted won’t fire until you explicitly trigger the request using the GraphRequest object. In most cases, you’ll call:
userData.executeAsync()
This is when the network request is actually sent, and once it finishes, your onCompleted method will log the result as you’ve defined.
A quick side note to avoid confusion:
If you were dealing with a function that returns a function type (like () -> Unit), assigning it to a variable would store the function itself without executing it. But that’s not the case here—newMeRequest returns a concrete GraphRequest instance, so invoking it creates that instance right away.
To sum up:
GraphRequest.newMeRequest()runs immediately when you assign it touserData- It creates a request object (no network call yet)
- You need to call
executeAsync()(or similar) onuserDatato actually send the request and trigger your callback
内容的提问来源于stack exchange,提问作者Zorgan

