Error returned when trying to run a basic function in dart - function

I'm new to dart (coming from a python background), and I'm struggling to make a function work. I've created the following function:
void main() {
int number = 22;
Function evenChecker(int number) {
if ((number%2) == 0) {
print('$number is even');
} else {
print('$number is odd');
}
}
}
but is get the following error:
Error: A non-null value must be returned since the return type 'Function' doesn't allow null.
bin/hello_dart_project.dart:4
- 'Function' is from 'dart:core'.
Additionally, if anyone has any suggestions about a good dart learning resource, I'd highly appreciate the advice.
^

Unlike Python or JavaScript, there is no keyword to define functions in dart. Instead, we declare functions by starting with their return type:
void evenChecker(...) {...}
^^^^
// This is the return type. "void" means "returns the value null" or "doesn't return anything"

Related

Can I create an alias for a generic function? I get error "Cannot use generic function without instantiation"

I can define a generic function:
package hello
func IsZero[T int64|float64](value T) bool {
return value == 0
}
Then if I try to alias that function in another package, it fails:
package world
import "hello"
var IsZero = hello.IsZero
The above doesn't compile with:
cannot use generic function hello.IsZero without instantiation
Instead this works:
var IsZero = hello.IsZero[int64]
Is it possible to do this, using some other syntax?
That's not an alias. And you already have your answer, actually. But if you want a formal reference, from the language specs, Instantiations:
A generic function that is is not called requires a type argument list for instantiation
So when you attempt to initialize a variable of function type, the function hello.IsZero is not called, and therefore requires instantiation with specific type parameters:
// not called, instantiated with int64
var IsZero = hello.IsZero[int64]
At this point the variable (let's give it a different name for clarity) zeroFunc has a concrete function type:
var zeroFunc = IsZero[int64]
fmt.Printf("type: %T\n", zeroFunc)
Prints:
type: func(int64) bool
This might or might not be what you want, as this effectively monomorphises the function.
If you just want to have a local symbol, with the same implementation (or a tweaked version thereof), declaring a "wrapper" function works. Just remember that the type parameters of your wrapper can only be as strict or stricter than the wrapped one's
E.g. Given
IsZero[T int64 | float64](v T)
your wrapper can not be
WrapIsZeroPermissive[T int64 | float64 | complex128](v T) bool {
return IsZero(v) // does not compile, T's type set is a superset
}
but can be
WrapIsZeroStricter[T int64](v T) bool {
return IsZero(v) // ok, T's type set is a subset
}
If the function is small, like in the question, it's probably easier to just vendor it:
package vendor
func thisIsJustCopy[T int64|float64](value T) bool {
return value == 0
}
but if the function is big, you can do it like this:
package world
import "hello"
func IsZero[T int64|float64](value T) bool {
return hello.IsZero(value)
}
I try to alias that function in another package
Aliases work for types only. Your code just tries to declare a variable.
Is it possible to do this, using some other syntax?
No.

Confused on how Swift nested functions work

For example, take this code:
func jediTrainer () -> ((String, Int) -> String) {
func train(name: String, times: Int) -> (String) {
return "\(name) has been trained in the Force \(times) times"
}
return train
}
let train = jediTrainer()
train("Obi Wan", 3)
I am completely confused as to what is going on in this function. jediTrainer takes no parameters, and returns a function called train. When we say "train = jediTrainer()" are we now storing the FUNCTION "train" into the variable called "train", as it returned that function that's now stored in the variable? Can you please break down what exactly is going on here into steps? Thank you so much!
In Swift functions are first class objects that means functions can be referenced by variables, passed as parameters and returned from other functions.
In your case jediTrainer() returns a function which is a nested function in itself. So let train is referring to train() function in jediTrainer. Now you could call that train function using train variable.
For more information on this please refer to Function Types and related topics here.
You also have an opinion of definining functions inside a bodies of other functions.These are called nested function .
By default Nested functions is hidden from outside world .It can still be called and used by its enclosing function .An enclosing function can also return one of nested functions ,thus allowing the nested function to be used in another scope .
func aFunc (flag:Book)->(Int)->Int
{
func plus ( input:Int )->Int
{
return input + 1
}
func minus ( input:Int )->Int
{
return input - 1
}
if (flag)
{
return plus
}
else
{
return minus
}
}

AS3 - Check if a callback function meets certain argument criteria?

If I set up a function that accepts a callback:
function loadSomething(path:String, callback:Function):void;
And that callback should accept a given type, for example a String to represent some loaded information:
function onLoaded(response:String):void;
// Load some data into onLoaded.
loadSomething("test.php", onLoaded);
Is it possible to assess the function that will be used for callback and ensure that it has both a given amount of arguments and that the argument accepts the correct type? e.g.
function broken(arg:Sprite):void;
// This should throw an error.
loadSomething("test.php", broken);
I don't think you should bother doing this kind of check as it would create an uncessary overhead. You can simply throw the exception when you do the callback:
try {
doCallback(response);
} catch(e:*) {
trace('Incompatible callback');
}
If you really want to do the check, you might be able to do it using reflection. Just call describeType(callback) from flash.utils and parse the XML.
One simple thing you can do is to check the number of acceptable arguments by calling length property on method closure like:
function some ( val1 : int, val2 : int ) : void { return; }
trace(some.length); // traces 2
Other much more complex method maybe is to use AS3Commons bytecode library. You can experiment with dynamic proxies.

How to define the return type of AS3 method that may return or not return a result?

public function t()
{
if(xxx)return xxx;
//don't return anything
}
How to define the return type for such method?
A function either has to return nothing, or return something - it can't do both. The reason being, what if you write this code:
var someValue = someFunction();
How would this code be handled if sometimes someFunction returned a value, and sometimes it didn't?
Your problem is a really common one, though, and there are several ways to work around it.
Sentinel Values
You can return special-case values that you treat as non-values (such as null, NaN, "", or -1). These special-case values are called sentinel values. The users of your function (maybe your own code) would check the result after calling it. If it gets one of the sentinel values back, it doesn't use the result.
Try-style Functions
You could also use a pattern commonly used in C#/.Net that they call "Try-methods", but you can call "Try-functions". Actionscript doesn't work exactly like C#, but we can get close enough for this pattern to work.
To do this, return Boolean, returning true if you have a value, and false if you don't. Then give your function an Object parameter, and populate a property with the actual return value:
function trySomeFunction(result:Object) : Boolean
{
if(xxx)
{
result.Value = xxx;
return true;
}
return false;
}
// ...
var result:Object = { Value:null };
if(trySomeFunction(result))
{
// Do something with the value here
}
Exceptions
If your method failed to do what it promised to do, you can throw an exception. Then you don't have to worry about what gets returned, because your code just dies.
Exceptions are great because people who call your code don't have to learn as much. They don't have to know that your function only succeeded if it doesn't return some magic value that is different for every function, they don't need to check if your function returns true/false, and they don't need to know that some property gets populated on an object when the function succeeded.
Without exceptions, if they forget to check for your special value, or the result of a "Try-function", an error might happen further on in the program. Or it might not happen at all, and the program will continue running, but be broken. In these cases, it is much harder to track down the problem.
With exceptions, your code just blows up the second it detects a problem, and gives you the line of code where your program realized it couldn't work correctly.
If it is normal and okay for your function to fail, though, you probably shouldn't throw an exception. You should probably use a "Try-function" or a sentinel value instead.
Everything that Merlyn says is fine, though perhaps a bit of overkill. If your method needs the potential to return null, then just pass xxx back whether it's null or not...
public function t():MyReturnType
{
return xxx;
}
... since you're going to have to do check the special condition in the calling method anyway:
public function caller():void
{
var value:MyReturnType = t();
if (value)
doSomethingPositive();
else
copeWithNullState();
}
Some people think that this is wrong and advocate creating a special 'null value' object in your return class, like this:
public class MyReturnType
{
public static const NULL:MyReturnType = new MyReturnType(null);
public function MyReturnType(identifier:String)
...
}
then in your function either return an interesting MyReturnType or NULL:
public function t():MyReturnType
{
return xxx || MyReturnType.NULL;
}
but then you've not really improved your caller method so why bother?
public function caller():void
{
var value:MyReturnType = t();
if (value != MyReturnType.NULL)
doSomethingPositive();
else
copeWithNullState();
}
Whatever you choose to do, eventually you're just going to have to test for special cases in the caller method. Personally I'd say it's better to keep it as simple as possible, and the special 'null value' in your class is over-complication.
I write plenty of functions that might return an object reference, but may also return null, like this:
public function findThingById( id:int ):MyThingType
{
... code here to search for/load/lookup thing with matching id
if (found)
{
return thing;
}
return null;
}
Wherever you call a function that might return null, you would either test the return value for null explicitly, or if you expect null just don't do anything with the return value. For built-in data types, you would use a special value rather than null (like NaN for Numbers illustrated above), but the principle is the same.
public function t():type
{
if(xxx)return xxx;
//don't return anything
}
so something like:
private function derp():void{
}
private function derp2():int{
}
private function derp3():Boolean{
}
etc
its always good practice to define the return type, and return an indicator variable if false (i.e return -1 for number), but if its really necessary you can do this:
public function t()
{
if(xxx)return xxx;
//don't return anything
}
don't specify a return type at all, and either it will return xxx or undefined, but I highly encourage using a return type.
But since flash runs on virtual memory it can basically adapt to your return type so it makes it a little flexible so you can return what ever.
EDIT:
public function t()
{
if(true){
return xxx; //xxx can by of any type
}
return NaN
}
EDIT:
so lets say you want the condition with a return type of int you would have
public function t():int
{
if(true){
return xxx; //where xxx != -1
}
return -1
}
this when we get back any number other then negative 1 we know the condition was true, but if we get -1 the condition was false. But if you numbers are any real numbers, use NaN keyword:
public function t():Number
{
if(true){
return xxx; //where xxx != -1
}
return NaN
}
this way if you get NaN back it means your condition was false
I should also mention that when your dealing with NaN use the isNaN() to determine if the return type was NaN or not:
example:
if(isNaN(t()) == true){
//if condition in function t() was false;
}
There is no way a single function can return void as well as returning a type. This is because void is not part of any inheritance chain, it is a top level concept meaning something very specific; it doesn't return anything.
Don't get confused between null and void, undefined and void, NaN and void. They are different concepts.
The answer to your question is simply that it can't, nor should it be done. When you hit a problem like this, it's good practice to step back and ask 'why' do you need to do this.
I would highly encourage that you mark this question as closed, and instead posted a higher level problem. For example,
How would I structure a class that has a variable xxx that does this and that and will be eventually set to a number when the user clicks. But if the user never clicks, it will be unset.... ecetera ecetera....
If you are 100% convinced you should do something like you're asking, you could 'fake' it by
function f():* {
var xxx:Number = 999;
if(xxx) {
return xxx;
} else {
return undefined;
}
}
var xx:* = f();
trace(xx);
But remember, from that point onwards you will need to check everytime xx is used to see if it undefined. Otherwise it will lead to errors.

what is the point of void in AS3

Simple question here, when void follows a function in AS3 what is it doing?
public function sayGoodbye():void { trace("Goodbye from MySubClass");}
void type indicates to the compiler that the function you have written will not return any value, in the other side if you indicate other type T than void the compiler expect that you return T.
Ex:
function foo(a:int):int { // here the compiler expect that somewhere
// in your function you return an int
return a;
}
void means that it has no return value. I.e., you can't use it in an expression.
void specifies that the function will return no value, or, to be more exact, the special undefined value type. Note that the function return can be used in an expression and it is the unique value of the undefined type.
In actionscript 3 to conform to the strict mode you need to specify variable types and function return types in order for the compiler to know what types to expect and to optimize your application.