I have a class that sorts a generic set of objects...
# getting-started
a
I have a class that sorts a generic set of objects by name, and had been using a Function Interface to pass in a Function for getting the generic object's name for sorting. I've been struggling to find the Kotlin equivalent to accomplish the same functionality.
b
could you just use a lambda?
a
I'm not sure how that would look syntactically in Kotlin. This is what I'm trying to convert:
Copy code
FuzzyFinder find = new FuzzyFinder<Kit>(new FuzzyFinder.LookupEntity<Kit>() {
                @Override
                public Result<Kit> lookup(Kit entity) {
                    return new Result<>(entity, entity.getQuery());
                }
            });
or rather:
Copy code
FuzzyFinder find = new FuzzyFinder<Kit>(entity -> new Result<>(entity, entity.getQuery()));
b
you could use a typealias
b
not sure i've got it all right, but maybe something like
Copy code
class Result<T>
abstract class Kit {
    abstract fun getQuery(): Result<Kit>
}

typealias FuzzyFinder = (Kit) -> Result<Kit>

val finder: FuzzyFinder = Kit::getQuery
a
It may have been helpful to include the Functional Interface as well:
Copy code
@FunctionalInterface public interface LookupEntity<T> { Result<T> lookup(T entity); }
The generic is currently passed into
FuzzyFinder<T>
and then inferred by
LookupEntity<T>
to return
Result<T>
b
so in kotlin that's just seen as "a function which takes a
T
and returns a
Result<T>
. you could do
typealias FuzzyFinder<T> = (T) -> Result<T>
and you can declare an instance
val finder: FuzzyFinder<XXX> = YYY
where
YYY
can be any function/function reference that takes a single
XXX
type and returns
Result<XXX>
a
would the typealias live within `FuzzyFinder`'s scope?
The 2nd part makes sense
b
don't think you can declare a typealias within a class
if that's what you mean
a
yeah, I'm still in the process of releasing my mind from OOP
d
Copy code
val list = objects.toMutableList()
list.sortBy { it.query }
I don't know what the point is of your result class. Given your description of what you need, I wrote the code above.
You should not release your mind from OOP at all, as kotlin is very much object oriented. Lambdas are used a lit more than in jva though, and for good reason, as most functions accepting them are inlined.
a
Given the description of what I need, it's for sorting a set of generic objects (https://docs.oracle.com/javase/tutorial/java/generics/types.html), which means there's no guaranteed contract for acquiring any given object's title/name.
I've solved my issue though, thanks.