Send an unknown method call: Difference between revisions

m
syntax highlighting fixup automation
(→‎{{header|Picat}}: code tag for functions)
m (syntax highlighting fixup automation)
Line 12:
=={{header|AutoHotkey}}==
This object has 3 methods, and asks the user to name one to call. Instead of using Func(), one could use a class definition.
<langsyntaxhighlight AHKlang="ahk">obj := {mA: Func("mA"), mB: Func("mB"), mC: Func("mC")}
InputBox, methodToCall, , Which method should I call?
obj[methodToCall].()
Line 25:
MsgBox Method C
}
</syntaxhighlight>
</lang>
 
=={{header|Bracmat}}==
<langsyntaxhighlight Bracmatlang="bracmat">(task=
( oracle
= (predicate="is made of green cheese")
Line 47:
& (SourceOfKnowledge..str$(generate !trueorlie))$!something
);
</syntaxhighlight>
</lang>
{{out|Example}}
<pre>{?} !task
Line 58:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
class Example
Line 79:
}
}
</syntaxhighlight>
</lang>
{{out}}
foo(5) = 47
Line 87:
$METHOD executes a named instance method for a specified instance of a designated class.
 
<langsyntaxhighlight lang="cos">Class Unknown.Example Extends %RegisteredObject
{
 
Line 100:
}
 
}</langsyntaxhighlight>
{{out|Examples}}
<pre>
Line 112:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(import '[java.util Date])
(import '[clojure.lang Reflector])
Line 132:
;; then we run the code using eval
(eval `(. date1 ~(symbol method) date2))
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Unknown methods are called just like any other function. Find the method-naming symbol using INTERN then call it with FUNCALL.
<langsyntaxhighlight lang="lisp">(funcall (intern "SOME-METHOD") my-object a few arguments)</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">local :object { :add @+ }
local :method :add
 
!. object! method 1 2</langsyntaxhighlight>
{{out}}
<pre>3</pre>
Line 150:
This example goes well with the object named <code>example</code> in [[Respond to an unknown method call#E]].
 
<langsyntaxhighlight lang="e">for name in ["foo", "bar"] {
E.call(example, name, [])
}</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.1 :
<langsyntaxhighlight lang="elena">import extensions;
class Example
Line 173:
console.printLine(methodSignature,"(",5,") = ",result)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 181:
=={{header|Factor}}==
Factor's object model is such that objects themselves don't contain methods — generic words do. So there is nothing different about invoking an unknown method than invoking an unknown word in general.
<langsyntaxhighlight lang="factor">USING: accessors kernel math prettyprint sequences words ;
IN: rosetta-code.unknown-method-call
 
Line 193:
! must specify vocab to look up a word
"rosetta-code.unknown-method-call"
lookup-word execute . ! 47</langsyntaxhighlight>
 
=={{header|Forth}}==
Line 201:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<langsyntaxhighlight lang="forth">include FMS-SI.f
include FMS-SILib.f
 
Line 212:
x p: 42 \ send the print message ( p: ) to x to verify the contents
 
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 238:
// interpret first return value as int
fmt.Println(r[0].Int()) // => 42
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="grrovy">class Example {
def foo(value) {
"Invoked with '$value'"
Line 251:
def arg = "test value"
 
assert "Invoked with 'test value'" == example."$method"(arg)</langsyntaxhighlight>
 
==Icon and {{header|Unicon}}==
<langsyntaxhighlight Uniconlang="unicon">procedure main()
x := foo() # create object
x.m1() # static call of m1 method
Line 265:
method m1(x)
end
end</langsyntaxhighlight>
 
For more information on this see [[Respond_to_an_unknown_method_call#Icon_and_Unicon|Respond to an unknown method call]].
Line 271:
=={{header|Io}}==
String literal "foo" may be replaced by any expression resulting in a string.
<langsyntaxhighlight Iolang="io">Example := Object clone
Example foo := method(x, 42+x)
 
name := "foo"
Example clone perform(name,5) println // prints "47"</langsyntaxhighlight>
 
=={{header|J}}==
Line 283:
There are other methods as well, e.g., '''<tt>@.</tt>''','''<tt>`:</tt>''', and '''<tt>^:</tt>''', though these are designed to consume gerunds (pre-parsed ASTs) rather than strings (though, of course, a pre-processor can always be provided to convert strings into ASTs before feeding them to these operators).
 
'''Example''':<langsyntaxhighlight lang="j"> sum =: +/
prod =: */
count =: #
Line 303:
3
nameToDispatch (128!:2) 1 2 3
3</langsyntaxhighlight>
 
=={{header|Java}}==
Using reflection
<langsyntaxhighlight lang="java">import java.lang.reflect.Method;
 
class Example {
Line 324:
System.out.println(result); // prints "47"
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
String literal "foo" may be replaced by any expression resulting in a string
<langsyntaxhighlight lang="javascript">example = new Object;
example.foo = function(x) {
return 42 + x;
Line 334:
 
name = "foo";
example[name](5) # => 47</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">const functions = Dict{String,Function}(
"foo" => x -> 42 + x,
"bar" => x -> 42 * x)
 
@show functions["foo"](3)
@show functions["bar"](3)</langsyntaxhighlight>
 
{{out}}
Line 352:
=={{header|Kotlin}}==
When you try to compile the following program, it will appear to the compiler that the local variable 'c' is assigned but never used and a warning will be issued accordingly. You can get rid of this warning by compiling using the -nowarn flag.
<langsyntaxhighlight lang="scala">// Kotlin JS version 1.1.4-3
 
class C {
Line 364:
val f = "c.foo"
js(f)() // invokes c.foo dynamically
}</langsyntaxhighlight>
 
{{out}}
Line 372:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define mytype => type {
public foo() => {
return 'foo was called'
Line 382:
local(obj = mytype, methodname = tag('foo'), methodname2 = tag('bar'))
#obj->\#methodname->invoke
#obj->\#methodname2->invoke</langsyntaxhighlight>
{{out}}
<pre>foo was called
Line 388:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">obj = script("MyClass").new()
-- ...
method = #foo
arg1 = 23
res = call(method, obj, arg1)</langsyntaxhighlight>
 
=={{header|Logtalk}}==
For this task, we first define a simple object with a single method:
<langsyntaxhighlight lang="logtalk">:- object(foo).
 
:- public(bar/1).
bar(42).
 
:- end_object.</langsyntaxhighlight>Second, we define another object that asks the user for a message to be sent to the first object:<langsyntaxhighlight lang="logtalk">
:- object(query_foo).
 
Line 412:
write(Message), nl.
 
:- end_object.</langsyntaxhighlight>After compiling and loading both objects, we can try:
| ?- query_foo::query.
Message: bar(X).
Line 419:
=={{header|Lua}}==
Don't forget to pass the object for methods!
<langsyntaxhighlight lang="lua">local example = { }
function example:foo (x) return 42 + x end
 
local name = "foo"
example[name](example, 5) --> 47</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Creates a dialog box where one can type a function (Sin, Cos, Tan ...) and then a second dialog box for a value.
<syntaxhighlight lang="text">ToExpression[Input["function? E.g. Sin",]][Input["value? E.g. 0.4123"]]</langsyntaxhighlight>
{{out}}
<pre>Input: Sin
Line 436:
 
 
<syntaxhighlight lang="matlab">
<lang Matlab>
funName = 'foo'; % generate function name
feval (funNAME, ...) % evaluation function with optional parameters
Line 442:
funName = 'a=atan(pi)'; % generate function name
eval (funName, 'printf(''Error\n'')')
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface Example : NSObject
Line 466:
}
return 0;
}</langsyntaxhighlight>
The <code>performSelector: ...</code> methods can only be used with methods with 0 - 2 object arguments, and an object or <code>void</code> return type. For all other calls, one can create an <code>NSInvocation</code> object and invoke it, or directly call one of the <code>objc_msgSend</code> family of runtime functions.
 
Line 472:
 
A method object can be retrieved from its name using asMethod.
<langsyntaxhighlight Oforthlang="oforth">16 "sqrt" asMethod perform</langsyntaxhighlight>
Others :
Line 480:
 
A generic way to search a word into the dictionary in to use find method :
<langsyntaxhighlight Oforthlang="oforth">16 "sqrt" Word find perform</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">foo()=5;
eval(Str("foo","()"))</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">package Example;
sub new {
bless {}
Line 498:
package main;
my $name = "foo";
print Example->new->$name(5), "\n"; # prints "47"</langsyntaxhighlight>
 
=={{header|Phix}}==
Not specifically anything to do with objects, but you can construct routine names at runtime:
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">Hello</span><span style="color: #0000FF;">()</span>
Line 514:
<span style="color: #7060A8;">call_proc</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #000000;">erm</span><span style="color: #0000FF;">),{})</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
class Example {
function foo($x) {
Line 531:
// alternately:
echo call_user_func(array($example, $name), 5), "\n";
?></langsyntaxhighlight>
 
=={{header|Picat}}==
For functions use <code>apply/n</code> and for predicates <code>call/n</code>. The name of the function/predicate must be an atom and strings must be converted to atom, e.g. with <code>to_atom/1</code>.
<langsyntaxhighlight Picatlang="picat">go =>
println("Function: Use apply/n"),
Fun = "fib",
Line 562:
% A predicate
pyth(X,Y,Z) =>
Z = X**2 + Y**2.</langsyntaxhighlight>
 
{{out}}
Line 574:
=={{header|PicoLisp}}==
This can be done with the '[http://software-lab.de/doc/refS.html#send send]' function.
<langsyntaxhighlight PicoLisplang="picolisp">(send (expression) Obj arg1 arg2)</langsyntaxhighlight>
 
=={{header|Pike}}==
with [] instead of -> a string can be used to name a method:
<langsyntaxhighlight Pikelang="pike">string unknown = "format_nice";
object now = Calendar.now();
now[unknown]();</langsyntaxhighlight>
 
=={{header|PowerShell}}==
A random method using a random number:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$method = ([Math] | Get-Member -MemberType Method -Static | Where-Object {$_.Definition.Split(',').Count -eq 1} | Get-Random).Name
$number = (1..9 | Get-Random) / 10
Line 595:
 
$output | Format-List
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 605:
=={{header|Python}}==
String literal "foo" may be replaced by any expression resulting in a string
<langsyntaxhighlight lang="python">class Example(object):
def foo(self, x):
return 42 + x
 
name = "foo"
getattr(Example(), name)(5) # => 47</langsyntaxhighlight>
 
=={{header|Qi}}==
<syntaxhighlight lang="qi">
<lang qi>
(define foo -> 5)
 
Line 620:
 
(execute-function "foo")
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define greeter
Line 636:
(define unknown 'hello)
(dynamic-send greeter unknown "World")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Just for the fun of it, we'll mix in an anonymous role into an integer instead of defining a class.
<syntaxhighlight lang="raku" perl6line>my $object = 42 but role { method add-me($x) { self + $x } }
my $name = 'add-me';
say $object."$name"(5); # 47</langsyntaxhighlight>
The double quotes are required, by the way; without them the variable would be interpreted as a hard ref to a method.
 
Line 649:
You may replace :foo, :bar or "bar" with any expression that returns a Symbol or String.
 
<langsyntaxhighlight lang="ruby">class Example
def foo
42
Line 662:
Example.new.send( :bar, 1, 2 ) { |x,y| x+y } # => 3
args = [1, 2]
Example.new.send( "bar", *args ) { |x,y| x+y } # => 3</langsyntaxhighlight>
 
Object#send can also call protected and private methods, skipping the usual access checks. Ruby 1.9 adds Object#public_send, which only calls public methods.
 
{{works with|Ruby|1.9}}
<langsyntaxhighlight lang="ruby">class Example
private
def privacy; "secret"; end
Line 677:
e.public_send :publicity # => "hi"
e.public_send :privacy # raises NoMethodError
e.send :privacy # => "secret"</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight lang="scala">class Example {
def foo(x: Int): Int = 42 + x
}
Line 691:
assert(meth.invoke(example, 5.asInstanceOf[AnyRef]) == 47.asInstanceOf[AnyRef], "Not confirm expectation.")
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">class Example {
method foo(x) {
42 + x
Line 704:
 
say obj.(name)(5) # prints: 47
say obj.method(name)(5) # =//=</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">Object subclass: #Example.
 
Example extend [
Line 715:
symbol := 'foo:' asSymbol. " same as symbol := #foo: "
 
Example new perform: symbol with: 5. " returns 47 "</langsyntaxhighlight>
The <code>perform:with:with:</code> family of methods exist for methods with 0 - 2 (3 in [[GNU Smalltalk]]) arguments. For methods with more arguments, use <code>perform:withArguments:</code>, which takes an array of arguments.
 
Line 727:
The first case is used for interfacing with legacy Objective-C libraries. Objective-C is heavily dynamic with Smalltalk-style message passing. So Swift must be able to participate in this.
 
<langsyntaxhighlight lang="swift">import Foundation
 
class MyUglyClass: NSObject {
Line 738:
let someObject: NSObject = MyUglyClass()
 
someObject.perform(NSSelectorFromString("myUglyFunction"))</langsyntaxhighlight>
 
{{out}}
Line 748:
One of Swift's goals is to able to effectively bridge to dynamic languages such as Python and JavaScript. In order to facilitate more natural APIs, Swift provides the <code>@dynamicCallable</code> and <code>@dynamicMemberLookup</code> attributes which allow for runtime handling of method calls.
 
<langsyntaxhighlight lang="swift">@dynamicCallable
protocol FunDynamics {
var parent: MyDynamicThing { get }
Line 832:
.subtract(adding: 10, subtracting: 14)
 
print(thing.n)</langsyntaxhighlight>
 
{{out}}
Line 840:
=={{header|Tcl}}==
Method names are really just strings, i.e., ordinary values that can be produced by any mechanism:
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
oo::class create Example {
method foo {} {return 42}
Line 853:
for {set i 1} {$i <= 4} {incr i} {
$eg $i ...
}</langsyntaxhighlight>
{{out|The above produces this output}}
42
Line 862:
 
=={{header|Wren}}==
<langsyntaxhighlight lang="ecmascript">import "meta" for Meta
class Test {
Line 875:
for (method in ["foo", "bar"]) {
Meta.eval("test.%(method)()")
}</langsyntaxhighlight>
 
{{out}}
Line 884:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">name:="len"; "this is a test".resolve(name)() //-->14</langsyntaxhighlight>
 
{{omit from|Ada}}
10,333

edits