Pitel
Pitel

Reputation: 5393

Comparator as lambda

I've the following method in Java library:

public void setColumnComparator(final int columnIndex, final Comparator<T> columnComparator)

Idea says it has the following prorotype:

setColumnComparator(columnIndex: Int, columnComparator: ((Any!, Any!) -> Int)!)

How can I use it? I know it will be String, so I want something like this, but it doesn't compile.

setColumnComparator(0, Comparator<String> { a, b -> a.compareTo(b) }

Upvotes: 4

Views: 627

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170723

If you look more carefully, you need to pass comparator which compares complete values, not values in the column. So let's say the type of data in your table is Car (so that you have a SortableTableView<Car>) and the first column contains model names. Then you'd write

setColumnComparator(0, { a, b -> a.modelName.compareTo(b.modelName) }

Or better:

setColumnComparator(0, compareBy({ it.modelName })

(see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/compare-by.html)

From the signature IDEA shows, you might have a SortableTableView<Any> or a SortableTableView<*> instead. This really should be changed to a more specific type. But even without it, if you could have a Car or a Book:

compareBy({ (it as? Car)?.modelName }, { (it as? Book)?.title })

Upvotes: 2

zsmb13
zsmb13

Reputation: 89548

If you know for sure that your SortableTableView's generic type parameter is String, you could cast it to a SortableTableView<String> and then make the call to it:

(tableView as SortableTableView<String>).setColumnComparator(1, { x, y ->
    x.compareTo(y)
})

Alternatively, you could cast the parameters that the Comparator takes individually:

tableView.setColumnComparator(1, { x, y -> 
    (x as String).compareTo(y as String) 
})

Upvotes: 1

Related Questions