views:

49

answers:

3

We're converting some .NET 3.5 code to Java (Android).

This Java code gives the error:

Syntax error on token "Chapters", VariableDeclaratorId expected after this token

this.add (new Book() {Chapters=50, OneBasedBookID = 1, 
Long = "Bahai", Short = "ba", Color = c,   BookType = b; });

The types are all correct.

+5  A: 

You are using .NET/C#'s ability to initialize properties at the time you create your object. To do it in Java (or in older C#), you are going to have to do it the long way.

Book book = new Book();
book.Chapters = 50;
// etc
this.add(book);
Anthony Pegram
+3  A: 

Java doesn't have object initializers, so this syntax is not valid.

Instead, you're probably looking to do something like this:

Book book = new Book();

book.Chapters = 50;
book.OneBasedBookID = 1;
book.Long = "Bahai";
book.Short = "ba";
book.Color = c;
book.BookType = b;

this.add(book);

Also note that Java has no concept of "proper" properties either, and typical "good" practice is to use getters/setters, and to not name your variables starting with upper-case letters. This wouldn't work for your Long and Short members though, and overall these practices may not provide any value in your scenario anyway.

Tim Stone
+1  A: 

You could use the anonymous class initializer trick:

this.add (new Book() {{
    Chapters=50;
    OneBasedBookID = 1;
    Long = "Bahai";
    Short = "ba";
    Color = c;
    BookType = b;
}});
krock
does this work in Java?
Louis Rhys
(+1) I'm not sure about creating the anonymous class just for this purpose, and it does require that you declare `c` and `b` to be final, but this is an interesting approach (and has the benefit of matching the OP's desired syntax closely).
Tim Stone
@Loius - Yeah, it's similar to delcaring a non-static inner class, and then assigning values to the enclosing type's members. You end up with an anonymous type though, not an actual `Book`.
Tim Stone