Java doesn't. (It's just convention)
Delphi does.
I believe C# does.
What other languages do?
Edit:
I should have given an example:
Delphi: (beware, it's been a while, I may get this wrong)
type
TSomething = class
fEmployeeNum: String;
property employeeNum: String read fEmployeeNum write setEmployeeNum;
end;
procedure TSomething.setEmployeeNum(var val: String);
begin
fEmployeeNum := val;
end;
Python does.
class SomeClass( object ):
def f_get( self ):
return self.value
fprop = property( f_get )
Code for setter is similar.
C# does (just to provide an example):
class Foo
{
public string Bar { get; private set; }
public string Bargain
{
get { return this._Bargain; }
set { this._Bargain = value; }
}
private string _Bargain;
}
Ruby does through attr_reader, attr_writer, and attr_accessor (for read/write):
class SomeClass
attr_reader :foo #read-only
attr_writer :bar #write-only
attr_accessor :baz #read and write
...
end
VB.NET does through the Property keyword.
C++ doesn't under the standard, but you can create the capacity through templates.
objective c and you can be lazy with the synthesize keyword.
In Perl 6,
use v6;
sub foo() is rw {
state $foo;
return new Proxy:
FETCH => method { return $foo },
STORE => method($to) { $foo = $to };
}
foo = "Hello, world!";
say foo;
...at least in theory. Doesn't seem to work with Rakudo r38250.
Related
The Golang "fmt" package has a dump method called Printf("%+v", anyStruct). I'm looking for any method to dump a struct and its methods too.
For example:
type Foo struct {
Prop string
}
func (f Foo)Bar() string {
return f.Prop
}
I want to check the existence of the Bar() method in an initialized instance of type Foo (not only properties).
Is there any good way to do this?
You can list the methods of a type using the reflect package. For example:
fooType := reflect.TypeOf(&Foo{})
for i := 0; i < fooType.NumMethod(); i++ {
method := fooType.Method(i)
fmt.Println(method.Name)
}
You can play around with this here: http://play.golang.org/p/wNuwVJM6vr
With that in mind, if you want to check whether a type implements a certain method set, you might find it easier to use interfaces and a type assertion. For instance:
func implementsBar(v interface{}) bool {
type Barer interface {
Bar() string
}
_, ok := v.(Barer)
return ok
}
...
fmt.Println("Foo implements the Bar method:", implementsBar(Foo{}))
Or if you just want what amounts to a compile time assertion that a particular type has the methods, you could simply include the following somewhere:
var _ Barer = Foo{}
I have a class like this:
in foo.groovy
class Foo {
String thing
Integer other
Foo(String thing) {
this.thing = thing
}
Foo(Integer other) {
this.other = other
}
}
return Foo.class
Now I would like to invoke these constructors. What I am doing is:
Other.groovy
def foo = evaluate(new File(ClassLoader.getSystemResource('foo.groovy').file)).newInstance(10)
def foo2 = evaluate(new File(ClassLoader.getSystemResource('foo.groovy').file)).newInstance("thing")
But this doesn't seem like the correct way of doing it. Ideally I would like to actually name the file Foo.groovy but then I get an error because it automatically declares the class for me. Basically, I want it to work like a classic Java class
Maybe I'm missing something here, but:
class Foo {
String thing
Integer other
Foo(String thing) {
this.thing = thing
}
Foo(Integer other) {
this.other = other
}
}
def x = new Foo(10)
assert x.other == 10 // true
def y = new Foo("foo")
assert y.thing == "foo" // true
What are you trying to accomplish here other than that?
Edit: Try it here.
Say for example you have something like this, trying to make the example as simple as possible.
type Home struct {
Bedroom string
Bathroom string
}
How do you pass the field name, or can you, to a function?
func (this *Home) AddRoomName(fieldname, value string) {
this.fieldname = value
}
Obviously that does not work... The only way I can see to do this is to use two functions which adds a lot of extra code when the struct gets really big and has a lot of similar code.
func (this *Home) AddBedroomName(value string) {
this.Bedroom = value
}
func (this *Home) AddBathroomName(value string) {
this.Bathroom = value
}
The only way that I am aware of is to use reflection:
func (this *Home) AddRoomName(fieldname, value string) {
h := reflect.ValueOf(this).Elem()
h.FieldByName(fieldname).Set(reflect.ValueOf(value))
return
}
http://play.golang.org/p/ZvtF_05CE_
One more idea that comes to my mind is like this, not sure if it makes sense in your case though:
func Set(field *string, value string) {
*field = value
}
home := &Home{"asd", "zxc"}
fmt.Println(home)
Set(&home.Bedroom, "bedroom")
Set(&home.Bathroom, "bathroom")
fmt.Println(home)
http://play.golang.org/p/VGb69OLX-X
Use type assertions on an interface value:
package main
import "fmt"
type Test struct {
S string
I int
}
func (t *Test) setField(name string, value interface{}) {
switch name {
case "S":
t.S = value.(string)
case "I":
t.I = value.(int)
}
}
func main() {
t := &Test{"Hello", 0}
fmt.Println(t.S, t.I)
t.setField("S", "Goodbye")
t.setField("I", 1)
fmt.Println(t.S, t.I)
}
I'm trying to pass a Class reference and instantiate it in a function. This doesn't work:
function foo(myClassRef:Class):Void {
var myVar = new myClassRef();
}
foo(MyClass);
It gives Unexpected (.
Is this possible in Haxe 3?
Class has a Type Parameter, so if you're going to accept a class as an argument, you need to specify a type parameter.
Accept any class:
function foo(myClassRef:Class<Dynamic>):Void {
var myVar = Type.createInstance( myClassRef, [constructorArg1, constructorArg2....] );
trace( Type.typeof(myVar) );
}
Accept only "sys.db.Object" class or sub classes:
function foo(myClassRef:Class<sys.db.Object>):Void {
var myVar = Type.createInstance( myClassRef, [] );
trace( Type.typeof(myVar) );
}
Haxe 3 also allows generic functions:
#:generic function foo<T:Dynamic>(t:Class<T>) {
var myVar = new T();
trace( Type.typeof(myVar) );
}
Here you declare the function to be generic, which means that for each different type parameter, a different version of the function will be compiled. You accept Class, where T is the type parameter - in this case, dynamic, so it will work with any class. Finally, using generic functions let's you write new T(), which may seem a more natural syntax, and there may be performance benefits on some platforms.
It is possible in Haxe3 and Haxe2
function foo<T>(myClassRef:T):Void {
var myVar = new T();
}
Note: Haxe3 class (where foo is implemented) must be #:generic if you want new T() to work.
Haxe2 is another story:
function foo<T>(myClassRef:Class<T>):Void {
var myVar = Type.createEmptyInstance(Type.getClass(myClassRef));
}
After creating a struct like this:
type Foo struct {
name string
}
func (f Foo) SetName(name string) {
f.name = name
}
func (f Foo) GetName() string {
return f.name
}
How do I create a new instance of Foo and set and get the name?
I tried the following:
p := new(Foo)
p.SetName("Abc")
name := p.GetName()
fmt.Println(name)
Nothing gets printed, because name is empty. So how do I set and get a field inside a struct?
Working playground
Commentary (and working) example:
package main
import "fmt"
type Foo struct {
name string
}
// SetName receives a pointer to Foo so it can modify it.
func (f *Foo) SetName(name string) {
f.name = name
}
// Name receives a copy of Foo since it doesn't need to modify it.
func (f Foo) Name() string {
return f.name
}
func main() {
// Notice the Foo{}. The new(Foo) was just a syntactic sugar for &Foo{}
// and we don't need a pointer to the Foo, so I replaced it.
// Not relevant to the problem, though.
p := Foo{}
p.SetName("Abc")
name := p.Name()
fmt.Println(name)
}
Test it and take A Tour of Go to learn more about methods and pointers, and the basics of Go at all.
Setters and getters are not that idiomatic to Go.
Especially the getter for a field x is not named GetX
but just X.
See http://golang.org/doc/effective_go.html#Getters
If the setter does not provide special logic, e.g.
validation logic, there is nothing wrong with exporting
the field and neither providing a setter nor a getter
method. (This just feels wrong for someone with a
Java background. But it is not.)
For example,
package main
import "fmt"
type Foo struct {
name string
}
func (f *Foo) SetName(name string) {
f.name = name
}
func (f *Foo) Name() string {
return f.name
}
func main() {
p := new(Foo)
p.SetName("Abc")
name := p.Name()
fmt.Println(name)
}
Output:
Abc