"Int should be Void -> Int" when comparing two integers - haxe

So this is a new one for me. When I try to compare 2 integers, the error tells me that Int should be Void -> Int, which is something I have never even seen before.
The code:
public static function whenTouchEnds(event:TouchEvent){
for (item in currentTouches){
if (item.getId == event.touchPointID){
currentTouches.remove(item);
trace("removed touch");
break;
}
}
}
Following the Haxe documentation, I also tried:
public static function whenTouchEnds(event:TouchEvent){
for (item in currentTouches){
if (item.getId == event.touchPointID) break;
}
}
And for the sake of trail and error (hobby programmer here) even tried:
public static function whenTouchEnds(event:TouchEvent){
for (item in currentTouches){
var itemID:Int = item.getId;
var touchID:Int = event.touchPointID;
if (itemID == touchID){
currentTouches.remove(item);
trace("removed touch");
break;
}
}
}
They all gave me the same error message "Int should be Void -> Int". Here is the Touch class I created which returns an Integer with the getId function:
class Touch
{
public var id:Int = 0;
public var xPos:Int = 0;
public var yPos:Int = 0;
public function new(Id:Int, X:Int, Y:Int)
{
id = Id;
xPos = X;
yPos = Y;
}
public function getX() : Int
{
return (xPos);
}
public function getY() : Int
{
return (yPos);
}
public function getId() : Int
{
return (id);
}
}
I'm not looking for a simple solution, but rather an explanation of what I am missing here. The more I learn, the better!
Cheers

The culprit is this line:
if (item.getId == event.touchPointID)
Since there's no parentheses, you're not actually calling the getId() function here - you're comparing it to an integer (which doesn't make sense). Try this instead:
if (item.getId() == event.touchPointID)
Void -> Int is Haxe's notation for a function type, specifically a function that takes no parameters (Void) and returns an integer. You're comparing such a function to an Int, hence the error message "Int should be Void -> Int".
A small code style critique: the get* functions in your Touch class don't really seem to serve any purpose, the variables are public anyway. If you ever want to do something more complex than just returning the variable in a getter function, you might want to look into using properties instead.

Related

Are accessors / mutators auto-defined in Groovy?

In the section on handling Java Beans with Groovy of Groovy In Action, I found this script (slightly modified):
class Book{
String title
}
def groovyBook = new Book()
// explicit way
groovyBook.setTitle('What the heck, really ?')
println groovyBook.getTitle()
// short-hand way
groovyBook.title = 'I am so confused'
println groovyBook.title
There are no such methods in the class Book so how does that work ?
Yes, they are auto defined and calling book.title is actually calling book.getTitle()
See http://groovy.codehaus.org/Groovy+Beans
You can see this in action with the following script:
def debug( clazz ) {
println '----'
clazz.metaClass.methods.findAll { it.name.endsWith( 'Name' ) || it.name.endsWith( 'Age' ) }.each { println it }
}
class A {
String name
int age
}
debug( A )
// Prints
// public int A.getAge()
// public java.lang.String A.getName()
// public void A.setAge(int)
// public void A.setName(java.lang.String)
// Make name final
class B {
final String name
int age
}
debug( B )
// Prints
// public int B.getAge()
// public java.lang.String B.getName()
// public void B.setAge(int)
// Make name private
class C {
private String name
int age
}
debug( C )
// Prints
// public int C.getAge()
// public void C.setAge(int)
// Try protected
class D {
protected String name
int age
}
debug( D )
// Prints
// public int D.getAge()
// public void D.setAge(int)
// And public?
class E {
public String name
int age
}
debug( E )
// Prints
// public int E.getAge()
// public void E.setAge(int)
Several notes:
For all property fields(public ones only), there are autogenerated accesors.
Default visibility is public. So, you should use private/protected keyword to restrict accessor generation.
Inside an accessor there is direct field access. like this.#title
Inside a constructor you have direct access to! This may be unexpected.
For boolean values there are two getters with is and get prefixes.
Each method with such prefixes, even java ones are treated as accessor, and can be referenced in groovy using short syntax.
But sometimes, if you have ambiguous call there may be class cast exception.
Example code for 4-th point.
class A{
private int i = 0;
A(){
i = 4
println("Constructor has direct access. i = $i")
}
void setI(int val) { i = val; println("i is set to $i"); }
int getI(){i}
}
def a = new A() // Constructor has direct access. i = 4
a.i = 5 // i is set to 5
println a.i // 5
​
4-th note is important, if you have some logic in accessor, and want it to be applied every time you call it. So in constructor you should explicit call setI() method!
Example for 7
class A{
private int i = 0;
void setI(String val) { println("String version.")}
void setI(int val) { i = val; println("i is set to $i"); }
}
def a = new A()
a.i = 5 // i is set to 5
a.i = "1s5" // GroovyCastException: Cannot cast object '1s5' with class 'java.lang.String' to class 'int'
​
So, as I see property-like access uses first declared accessor, and don't support overloading. Maybe will be fixed later.
Groovy generates public accessor / mutator methods for fields when and only when there is no access modifier present. For fields declared as public, private or protected no getters and setters will be created.
For fields declared as final only accessors will be created.
All that applies for static fields analogously.

Why following code doesnt override base class property in C++ CLI?

I'm a C# programmer and don't know much about C++.
Any idea why I'm getting error ?
ref class masterWeapon{
public :
virtual property int Slot {
int get(){
return -1;
}
}
};
ref class Weapon1 : masterWeapon{
public :
virtual property int Slot{
//following like throw an error : cannot override base class method
int get() override = masterWeapon::Slot::get{
return 1;
}
}
};
Just remove the = masterWeapon::Slot::get portion and it will compile. If you read the error message that accompanies C3764 it makes this a bit more obvious (but not 100%):
...because the base method is explicitly overridden by 'Weapon1::Slot::get'
Giving us the following code:
ref class Weapon1 : masterWeapon{
public :
virtual property int Slot {
int get() override {
return 1;
}
}
};
Which when run against:
masterWeapon^ weapon1 = gcnew masterWeapon();
masterWeapon^ weapon2 = gcnew Weapon1();
Console::WriteLine(L"weapon1->Slot = {0}", weapon1->Slot);
Console::WriteLine(L"weapon2->Slot = {0}", weapon2->Slot);
Results in:
weapon1->Slot = -1
weapon2->Slot = 1

How to mock a single method for a class?

I'm new to using a Mocking framework to mock objects for unit testing. I'm currently using Rhino Mocks and I would think it would have a method to do what I'm not finding it. Here is a LinqPad program (just copy and paste it in a C# program query and it will just work) that shows what I'm trying to do:
public interface MyTest{
int A(int i);
string B(int i);
}
/// This is an actual class that is a black box to me.
public class ActualClass : MyTest {
public int A(int i){
// Does some work
return ++i;
}
public string B(int i){
return A(i).ToString();
}
}
/// I'd like to create a mocked class that uses an instance of the actual class
/// to provide all of the implementations for the interface except for a single method
/// where I can check the parameter values, and provide my own return value,
/// or just call the actual class
public class MockedClass : MyTest {
private ActualClass _actual;
public MockedClass(ActualClass actual){
_actual = actual;
}
public int A(int i){
if(i == 1){
return 10;
}else{
return _actual.A(i);
}
}
public string B(int i){
return _actual.B(i);
}
}
void Main()
{
var mock = new MockedClass(new ActualClass());
mock.A(0).Dump();
mock.A(1).Dump();
mock.A(2).Dump();
mock.B(0).Dump();
mock.B(1).Dump();
mock.B(2).Dump();
}
Results:
1
10
3
1
2
3
What do I do to mock this out for unit testing. Do I need some sort of Dependency Injector?
Yes, you can change the return value of a mocked object based on the parameters passed in. I wouldn't take the approach of mixing a real dependency and a mocked dependency -- too much opportunity for a bug in the real dependency to creep in to your testing.
Here's an example you could use on your MyTest interface that examines the input argument of the mocked method and sets a return value accordingly:
var mock = MockRepository.GenerateStub<MyTest>();
mock.Stub(m => m.A(Arg<int>.Is.Anything))
.Return(99)
.WhenCalled(mi =>
{
var arg = Convert.ToInt32(mi.Arguments[0]);
switch (arg)
{
case 0:
mi.ReturnValue = 10;
break;
case 1:
mi.ReturnValue = 20;
break;
case 2:
mi.ReturnValue = 30;
break;
default:
mi.ReturnValue = -1;
break;
}
});
Note that the "Return(99)" is needed because when you stub a method that returns a value, Rhino.Mocks requires that you either define an exception to be thrown or define a return value. Even though we don't use the return value (since we provide our own inside the WhenCalled handler), it still must be defined or Rhino.Mocks will thrown an exception the first time the stub is called.

C#: is it possible to create an object that has a value of its "default property" when referenced?

Is it possible to create an object with a constructor parameter which returns a property value when referenced, without using dot notation? Here's a few examples:
public class myObject
{
public string myObject {get; private set;}
public myObject( string tempstring)
{
this.myObject = tempstring.ToUpper();
}
}
var a = new myObject("somevalue");
Console.WriteLine( myObject ); // outputs the string "SOMEVALUE"
Here's another attempt:
public class myInt
{
public int myInt {get; private set;}
public myInt(string tempInt)
{ this.myInt = Convert.ToInt32(tempInt);
}
}
var a = new myInt("3");
var b = a + a; // ends up being an int datatype value of 6
I know I could always do var b = a.myInt + a.myInt. I guess I could create a static class with a static function that converts a parameter each time to a result, but it wouldn't maintain state.
Just curious. It would make what I am actually trying to do much less difficult.
In the first case, yes. Override the ToString method.
public class myObject
{
public string myValue {get; private set;}
public myObject( string tempstring)
{
this.myValue = tempstring.ToUpper();
}
public override string ToString()
{
return myValue;
}
}
In the second case, sort of. You shouldn't try to overload operators to offer unexpected behavior. Create a method to perform behavior that wouldn't make sense when reading the code. What you are suggesting (returning an int) would definitely not be expected by me to return an int (mostly because of the var rather than a strictly defined type). Using the + operator to return a new myInt object would make sense. Using the + operator return an int would not.
You could overload the + operator to return a new myInt object, and then also add an implicit cast to int. Just make sure it makes sense, and that it is readable.
Within the class, you could use:
public static implicit operator int(myInt m)
{
return myValue;
}
public static myInt operator +(myInt left, myInt right)
{
// requires constructor that takes int
return new myInt(left.myValue + right.myValue);
}
Of course, you could go the direct route, but again only use it when it makes it more readable and not less (note, just like methods operators cannot be overloaded simply by return type, so you'd have to pick between the two).
public static int operator +(myInt left, myInt right)
{
return left.myValue + right.myValue;
}
How about implicit conversions. See http://msdn.microsoft.com/en-us/library/z5z9kes2(VS.71).aspx

Can extension methods modify extended class values?

I was just trying to code the following extension method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _4Testing
{
static class ExtensionMethods
{
public static void AssignMe(this int me, int value)
{
me = value;
}
}
}
But it is not working, i mean, can I use an extension method to alter values from extended classes? I don't want to change void return type to int, just changing extended class value. Thanks in advance
Your example uses int, which is a value type. Classes are reference types and behaves a bit differently in this case.
While you could make a method that takes another reference like AssignMe(this MyClass me, MyClass other), the method would work on a copy of the reference, so if you assign other to me it would only affect the local copy of the reference.
Also, keep in mind that extension methods are just static methods in disguise. I.e. they can only access public members of the extended types.
public sealed class Foo {
public int PublicValue;
private int PrivateValue;
}
public static class FooExtensions {
public static void Bar(this Foo f) {
f.PublicValue = 42;
// Doesn't compile as the extension method doesn't have access to Foo's internals
f.PrivateValue = 42;
}
}
// a work around for extension to a wrapping reference type is following ....
using System;
static class Program
{
static void Main(string[] args)
{
var me = new Integer { value = 5 };
int y = 2;
me.AssignMe(y);
Console.WriteLine(me); // prints 2
Console.ReadLine();
}
public static void AssignMe(this Integer me, int value)
{
me.value = value;
}
}
class Integer
{
public int value { get; set; }
public Integer()
{
value = 0;
}
public override string ToString()
{
return value.ToString();
}
}
Ramon what you really need is a ref modifier on the first (i.e. int me ) parameter of the extension method, but C# does not allow ref modifier on parameters having 'this' modifiers.
[Update]
No workaround should be possible for your particular case of an extension method for a value type. Here is the "reductio ad absurdum" that you are asking for if you are allowed to do what you want to do; consider the C# statement:
5.AssignMe(10);
... now what on earth do you think its suppose to do ? Are you trying to assign 10 to 5 ??
Operator overloading cannot help you either.
This is an old post but I ran into a similar problem trying to implement an extender for the String class.
My original code was this:
public static void Revert(this string s)
{
char[] xc = s.ToCharArray();
s = new string(xc.Reverse());
}
By using the new keyword I am creating a new object and since s is not passed by reference it will not be modified.
I changed it to the following which provides a solution to Ramon's problem:
public static string Reverse(this string s)
{
char[] xc = s.ToCharArray();
Array.Reverse(xc);
return new string(xc);
}
In which case the calling code will be:
s = s.Reverse();
To manipulate integers you can do something like:
public static int Increment(this int i)
{
return i++;
}
i = i.Increment();

Resources