3

I have edited my example to show a more practical example of what I'm trying to achieve. I would like to understand what I should specify as the second type when instantiating the new TableCell object within the Lambda expression, given the types being passed into the method.

Thanks in advance for any help.

void setTableCellStuff (TableColumn <Object, ?> tableCell) {
    tableCell.setCellFactory(arg0 -> 
        new TableCell <Object, ?> () // cannot use ? in instantiator.
    );
}
Matt
  • 95
  • 6
  • Why do you have to reuse the `col` variable? Would you have thie problem if you used a new variable every time? There could be an issue with object lifetime, but that's impossible to tell from this little bit of code. – SeverityOne Apr 17 '18 at 11:25
  • Could you provide a [minimal example](https://stackoverflow.com/help/mcve)? – OhleC Apr 17 '18 at 11:27
  • Hi @SeverityOne, thanks for your comment. As I said in my question I could declare a new variable for each column, but I was trying to be economical with my typing, particularly as I have about 30 columns. So I wanted to know if what I'm doing is possible, and also hoping to understand a little bit more about generics. Thanks! – Matt Apr 17 '18 at 11:28
  • @ohlec here you are: TableColumn col = new TableColumn ("Reference"); col.setCellFactory(arg -> new TableCell () { } ); – Matt Apr 17 '18 at 11:32

1 Answers1

2

You probably want this:

<T> void setTableCellStuff (TableColumn <Object, T> tableCell) {
    tableCell.setCellFactory(arg0 -> 
        new TableCell <Object, T> ()
    );
}

T could still be any type, but this way the type of table cell you construct matches the type of column you have.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87