Can I cast arguments to an object?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By welltraman

Hello,
Basically I want to do the same thing as how Node.get_node(NodePath path) allows String as an argument.

I want to allow my custom method to take arguments that are different from the expected arguments, but are convertible. (Since method overloading is not supported.)

Ultimately, what I’m hoping to do is, to allow:

Logger.warn("Error loading file!")

# instead of:
#Logger.warn(LogMsg.new("Error loading file!"))

When it’s expecting:

# Logger
func warn(m:LogMsg):
    push_warning(m.compose("WARNING"))

# LogMsg
func _init(message:String):
    _message = message

Is there any way this is possible?
Thanks.

I don’t quite follow. The parameter of the custom function needs to be a String or something else? Since GDScript is dynamically typed, any data type supported can be passed to the custom function. So the function can be programmed to behave one way for String input, or it could be programmed to behave for other input.

Ertain | 2021-10-16 09:15

:bust_in_silhouette: Reply From: aXu_AP

You can allow for any input and check if it’s of the right type and do necessary conversion:

func DoSomething(argument):
	if argument is String:
		pass
	elif argument is int:
		pass
	elif argument is Array:
		pass
	else:
		push_error("Argument type is not supported")

Function overloading would be cleaner approach (to get errors on compile time), but currently I think this is the way to do it.

:bust_in_silhouette: Reply From: yatharthmrk2405

Hello, I found a solution related to your question in the C# language . Here it is MethodBase.Invoke Method (System.Reflection) | Microsoft Learn

Hope this helps!

Happy Learning!!!