I actually posted this on the Unity forums, but none of my language-related questions ever seem to get answered there. So, let's say I have a function defined as so in Unity Script:
function GetSomething : SomeClass
{
return new SomeClass();
}
Where SomeClass is some class defined elsewhere. Now, I have a variable, theFunction, of type Function, and I want to make sure that it returns something, anything. So what I do is the following:
// theFunction is set to GetSomething somewhere else in the program.
var functionThatReturnsSomething = theFunction as function() : Object;
if (functionThatReturnsSomething != null)
//... call it and do stuff with the returned value.
Now unfortunately, in the above code functionThatReturnsSomething will be null. For it not to be null, I have to be more specific and cast to function() : SomeClass OR just override the function definition to return an Object as so:
function GetSomething : Object
{
return new SomeClass();
}
This is very annoying because its easy to forget to do :Object (especially since if you leave it out it will correctly infer it to be of return type SomeClass), and the result is not an error, but rather a very subtle bug since the cast fails. Is there any way to get the behavior I want, which is for it to properly downcast to function() : Object, the same way I can downcast normal objects?
The only thing i can think of is you forgot the parenthesis after the function name when you declare it. If i put everything into the following script, attach it to an object and run it then i get access to the function with no problems.
#pragma strict
import System.Collections.Generic;
function Start ()
{
// theFunction is set to GetSomething somewhere else in the program.
var functionThatReturnsSomething = GetSomething as function() : Object;
if (functionThatReturnsSomething != null)
{
//... call it and do stuff with the returned value.
Debug.Log(functionThatReturnsSomething);
}
else Debug.Log("null");
}
function GetSomething() : List.<int>
{
return new List.<int>();
}
Related
For some reason the compiler is complaining about this:
SynchronousFuture<void> setNewRoutePath(AppLink newLink) {
_currentLink = newLink;
// return null; // compiler really wants to see this null return...why?
}
But is happy with this:
Future<void> setNewRoutePath(AppLink newLink) async {
_currentLink = newLink;
}
Seems like async keyword is handling the implicit return here. Is there some equivalent for SynchronousFuture?
SynchronousFuture<void> setNewRoutePath(AppLink newLink) {
_currentLink = newLink;
// return null; // compiler really wants to see this null return...why?
}
You need a return value because your function is declared to return a non-void value, so it must return something. You could argue that all functions could implicitly return null if there's no explicit return statement, but that would be error-prone:
int f(String someValue) {
if (someCondition) {
return 42;
}
} // f didn't return anything if someCondition is false. Accidental or intentional?
Futures themselves aren't really special. If you have a non-async function that returns a Future, you must still have an explicit return statement:
Future<void> f() {
print('Hello world!');
} // Error: f doesn't end with a return statement.
However, the async keyword does a few things:
Primarily it enables the use of the await keyword.
It automatically wraps returned values in a Future. This includes implicit return values from void functions.
SynchronousFuture is just an ordinary class provided by Flutter that implements the Future interface. It is not special. It's not part of the Dart language, so there is not going to be any keyword that does automatic return value wrapping like what the async keyword does.
Also note that you should not just sprinkle return null statements in your function that returns SynchronousFuture. With an async function, a return; statement (or exiting the function without an explicit return statement) ultimately returns a Future<void>() to the caller. Callers expect to be able to call methods (e.g. .then()) on the returned Future to add completion callbacks. If you return null for a SynchronousFuture, calling .then() on it will result in a null pointer exception at runtime. You instead would need to use return SynchronousFuture<void>(null);.
I also should point out that the SynchronousFuture documentation states:
In general use of this class should be avoided as it is very difficult to debug such bimodal behavior.
so unless you have some clear need to use a SynchronousFuture, you're better off avoiding it.
Unless you have created a class called SynchronousFuture the compiler will complain as there is no class called SynchronousFuture in the dart standard library, so either you or a library you import must define this class.
In dart all async functions must have a return value of type Future<T>.
// return null; // compiler really wants to see this null
return...why?
Because Future is not the same as void, when you return a value in an async function, that value is subsequently used as value for the future, as future is a generic class.
I have a class in c++ that I'm wrapping into python with pybind11. That class has a std::function, and I'd like to control how the arguments to that function are dealt with (like return value policies). I just can't find the syntax or examples to do this...
class N {
public:
using CallbackType = std::function<void(const OtherClass*)>;
N(CallbackType callback): callback(callback) { }
CallbackType callback;
void doit() {
OtherClass * o = new OtherClass();
callback(o);
}
}
wrapped with
py::class_<OtherClass>(...standard stuff...);
py::class_<N>(m, "N")
.def(py::init<N::CallbackType>(),
py::arg("callback"));
I all works: I can do this in python:
def callback(o):
dosomethingwith(o)
k = N(callback)
, but I'd like to be able to control what happens when callback(o); is called - whether python then will take ownership of the wrapped o variable or not, basically.
I put a printout in the destructor of OtherClass, and as far as I can tell, it never gets called.
OK, I think I figured it out:
Instead of std::function, use a pybind11::function:
using CallbackType = pybind11::function
and then
void doit(const OtherClass &input) {
if (<I want to copy it>) {
callback(pybind11::cast(input, pybind11::return_value_policy::copy));
} else {
callback(pybind11::cast(input, pybind11::return_value_policy::reference));
}
}
I see nothing in pybind11/functional that allows you to change the ownership of the parameters at the point of call, as the struct func_wrapper used is function local, so can not be specialized. You could provide another wrapper yourself, but in the code you can't know whether the callback is a Python function or a bound C++ function (well, technically you can if that bound C++ function is bound by pybind11, but you can't know in general). If the function is C++, then changing Python ownership in the wrapper would be the wrong thing to do, as the temporary proxy may destroy the object even as its payload is stored by the C++ callback.
Do you have control over the implementation of class N? The reason is that by using std::shared_ptr all your ownership problems will automagically evaporate, regardless of whether the callback function is C++ or Python and whether it stores the argument or not. Would work like so, expanding on your example above:
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
namespace py = pybind11;
class OtherClass {};
class N {
public:
using CallbackType = std::function<void(const std::shared_ptr<OtherClass>&)>;
N(CallbackType callback): callback(callback) { }
CallbackType callback;
void doit() {
auto o = std::make_shared<OtherClass>();
callback(o);
}
};
PYBIND11_MODULE(example, m) {
py::class_<OtherClass, std::shared_ptr<OtherClass>>(m, "OtherClass");
py::class_<N>(m, "N")
.def(py::init<N::CallbackType>(), py::arg("callback"))
.def("doit", &N::doit);
}
I am trying to understand in depth how 'this' works in javascript.
All I have known about this so far is,
Every function has properties and whenever the function executes, it newly defines the this property.
this refers to the object that a function is invoked to (including window object in browser).
this refers to the scope of the object(where the object is defined) instead of referring to the object itself if you use arrow syntax when defining a function because arrow function does not newly defines its own this.
The examples below are to help understanding the behaviour of this
class Example {
constructor() {
this.name = 'John';
}
method1() { //case1 : Closure
console.log(this.name);
function method2() {
console.log(this.name);
}
method2();
}
}
const a = new Example()
a.method1();
function testing(callback) {
return callback();
}
class Example2 {
constructor() {
this.name = 'John';
}
method1() { //case2: callback
console.log(this.name);
testing(function() {
console.log(this.name);
})
}
}
const b = new Example2()
b.method1();
function testing(callback) {
return callback();
}
class Example3 {
constructor() {
this.name = 'John';
}
method1() { //case3: arrow syntax callback
console.log(this.name);
testing(() => {
console.log(this.name);
})
}
}
const c = new Example3()
c.method1(); // logs 'John'
// logs 'John'
function testing(callback) {
return callback();
}
class Example4 {
constructor() {
this.name = 'John';
}
method1() { // case4: calling method as callback
console.log(this.name);
}
render() {
testing(this.method1)
}
}
const d = new Example4()
d.render()
function testing(callback) {
return callback();
}
class Example5 {
constructor() {
this.name = 'John';
this.method1 = this.method1.bind(this);
}
method1() { //case5: bind method && calling method as callback
console.log(this.name);
}
render() {
testing(this.method1)
}
}
const d = new Example5()
d.render()
I wonder how those above cases are different and what the this refers to inside each inner function and callback. Could you please explain about it? thank you :)
Since the in-depth precise explanation can be pretty big and boring, here is an exceptional article by kangax that perfectly lays it out.
And just in case, if you need a short and ultra condensed version of it here goes my short and approximate take:
#
When you call a function the this is determined by the specific base value which is usually pointing to whatever is on the left of the .
in MemberExpression so in x.y() this === x, and in x.y.z() this === x.y.
In case of a simple CallExpression without the ., say just x(),
the base value is implicitly inferred to point to undefined, which in non-strict mode is converted to global window and in strict mode stays the same.
This is the general mental model which should cover 99% of all the day-to-day problems with drawing the this context out correctly.
Now on, to the actual cases:
CASE 1:
a.method1(); call has a base value a so the this inside of its body points to a, so no surprises here.
method2 has implicit base value undefined.method2, thus you have the TypeError which explicitly states that.
CASE 2:
function testing(callback) {
return callback();
}
callback() is called with implicit baseValue undefined, i.e. undefined.callback(),
and since the passed function is declared within class
testing(function() {
console.log(this.name);
})
that triggers the strict mode of code execution, that's why undefined is not converted again to global window, thus we have the same error as before.
CASE 3:
Arrow function
testing(() => {
console.log(this.name);
})
creates a hard binding from the this in enclosing scope,
basically under the hood it's the same as writing:
var _this = this;
testing((function() {
console.log(_this.name);
});
That's why you get the same object resolved as this
CASE 4:
Alright, this one is interesting and needs more mechanics explanation.
So when you pass this.method in:
render() {
testing(this.method1)
}
what you actually pass is not the reference this.method, but the actual underlying Function Object value, to which this reference points to, so
when it gets executed it has its this always pointing to undefined, here look, so it's pretty much "in stone".
And yes of course since this.method1 is declared in strict context again, thanks to enclosing es6 class, undefined remains undefined without conversion to global window.
CASE 5:
Same mechanics as with arrow function. Bind creates a wrapper function, which holds the cached this value, which is not possible to override with .call and .apply, the same as in => function.
Hope this clarifies a bit it all a bit.
I have to put some status data into the context object. This has to be done in lot of places so I thought it would be nice to solve this with AOP.
The problem is that I don't know how to access the callers parameter and the return value of the called method in the same advice. Is this possible at all?
public BusinessObject methodA(Context ctx, Param p) {
Status s = service.serviceMethod(p);
if (s.hasErrors())
{
ctx.put("error_key", s.getErrors());
}
...
}
One advantage of lambda expressions is that you have to evaluate a function only when you need its result.
In the following (simple) example, the text function is only evaluated when a writer is present:
public static void PrintLine(Func<string> text, TextWriter writer)
{
if (writer != null)
{
writer.WriteLine(text());
}
}
Unfortunately, this makes using the code a little bit ugly. You cannot call it with a constant or variable like
PrintLine("Some text", Console.Out);
and have to call it this way:
PrintLine(() => "Some text", Console.Out);
The compiler is not able to "infer" a parameterless function from the passed constant. Are there any plans to improve this in future versions of C# or am I missing something?
UPDATE:
I just found a dirty hack myself:
public class F<T>
{
private readonly T value;
private readonly Func<T> func;
public F(T value) { this.value = value; }
public F(Func<T> func) {this.func = func; }
public static implicit operator F<T>(T value)
{
return new F<T>(value);
}
public static implicit operator F<T>(Func<T> func)
{
return new F<T>(func);
}
public T Eval()
{
return this.func != null ? this.func() : this.value;
}
}
Now i can just define the function as:
public static void PrintLine(F<string> text, TextWriter writer)
{
if (writer != null)
{
writer.WriteLine(text.Eval());
}
}
and call it both with a function or a value.
I doubt that C# will get this feature, but D has it. What you've outlined is a suitable way to implement lazy argument evaluation in C#, and probably compiles very similarly to lazy in D, and in more pure functional languages.
All things considered, the four extra characters, plus optional white space, are not an exceptionally large price to pay for clear overload resolution and expressiveness in what is becoming a multi-paradigm strong-typed language.
The compiler is very good at inferring types, it is not good at inferring intent. One of the tricky things about all the new syntactic sugar in C# 3 is that they can lead to confusion as to what exactly the compiler does with them.
Consider your example:
() => "SomeText"
The compiler sees this and understands that you intend to create an anonymous function that takes no parameters and returns a type of System.String. This is all inferred from the lambda expression you gave it. In reality your lambda gets compiled to this:
delegate {
return "SomeText";
};
and it is a delegate to this anonymous function that you are sending to PrintLine for execution.
It has always been important in the past but now with LINQ, lambdas, iterator blocks, automatically implemented properties, among other things it is of the utmost importance to use a tool like .NET Reflector to take a look at your code after it is compiled to see what really makes those features work.
Unfortunately, the ugly syntax is all you have in C#.
The "dirty hack" from the update does not work, because it does not delay the evaluation of string parameters: they get evaluated before being passed to operator F<T>(T value).
Compare PrintLine(() => string.Join(", ", names), myWriter) to PrintLine(string.Join(", ", names), myWriter) In the first case, the strings are joined only if they are printed; in the second case, the strings are joined no matter what: only the printing is conditional. In other words, the evaluation is not lazy at all.
Well those two statements are completely different. One is defining a function, while the other is a statement. Confusing the syntax would be much trickier.
() => "SomeText" //this is a function
"SomeText" //this is a string
You could use an overload:-
public static void PrintLine(string text, TextWriter writer)
{
PrintLine(() => text, writer);
}
You could write an extension method on String to glue it in. You should be able to write "Some text".PrintLine(Console.Out); and have it do the work for you.
Oddly enough, I did some playing with lazy evaluation of lambda expressions a few weeks back and blogged about it here.
To be honest I don't fully understand your problem, but your solutions seems a tad complicated to me.
I think a problem I solved using lambda call is similar, maybe you could use it as inspiration: I want to see if a key exists in a dictionary, if not, I would need to execute a (costly) load operation.
public static class DictionaryHelper
{
public static TValue GetValueOrLambdaDefault<TKey, TValue> (this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> func)
{
if (dictionary.ContainsKey(key))
return dictionary[key];
else
return func.Invoke();
}
}
[TestClass]
public class DictionaryHelperTest
{
[TestMethod]
public void GetValueOrLambdaDefaultTest()
{
var dict = new Dictionary<int, string>();
try
{
var res1 = dict.GetValueOrLambdaDefault(1, () => LoadObject());
Assert.Fail("Exception should be thrown");
}
catch { /*Exception should be thrown*/ }
dict.Add(1, "");
try
{
var res1 = dict.GetValueOrLambdaDefault(1, () => LoadObject());
}
catch { Assert.Fail("Exception should not be thrown"); }
}
public static string LoadObject()
{
throw new Exception();
}
}