I’m trying to understand how official OOP works so I can implement it into my own OOP.
However, I don’t understand one specific part, where the video shows overriding an inherited function. The video can be found here.
After doing some research, I have found out that → means setting the type of the return of a function and ? means a type or nil, but I still don’t understand what the rest means and what the symbols do in that scenario.
--For the purpose of clarity, I have changed some of the variables' names in case someone hasn't watched the video
local parentClass = require(game.ReplicatedStorage.parentClass)
local OOPModule = {}
OOPModule.__Index = setmetatable(OOPModule, parentClass)
function OOPModule.new(...)
...
end
function OOPModule:Method(param: (() -> ())?) -- This is what I don't get
if true then
param()
end
end
when you call with a colon like :Method then it automatically creates self in the scope of that function
and its passing in param which is a function that accepts zero parameters and returns nothing, which is type annotated by () -> (), but then it also has a question mark around it to indicate it might not exist
so together, param which has the type (() -> ())? is a function that might exist, and if it exists then it accepts nothing and returns nothing
Your question is not about OOP but more about type annotations.
() -> () is the syntax for a function type, which means param should be a function. Inside the first parenthesis, you define the parameters types of the function, and in the second, you define the return types, if you leave them empty, then it means there are no parameters or no returns.
Yeah the example just shows an example method with a callback you’d pass as a parameter. I agree this is quite bad for an introduction to OOP to put such example as not everyone is familiar wlth how function types work. As explained () -> () is the type of a function whose body would look like this
function test() -- No param
--No return statement in body
end