Plagon
Plagon

Reputation: 3138

Kotlin map with function reference of a member function

Given the following two classes:

class Parent {
    val child : Child = Child()
}

class Child {
    fun doSomethingWithParent(parent : Parent) = Foo()
}

class Foo

And a list of Parents:

val list = List<Parent>(10){_ -> Parent()}

Instead of mapping with

list.map { it.child.doSomethingWithParent(it) } // works

to use a function reference to doSomethingWithParent like

// does not work
list.map(Child::doSomethingWithParent)
list.map(Parent::child::doSomethingWithParent)

Upvotes: 1

Views: 1717

Answers (2)

IR42
IR42

Reputation: 9672

You can't do this

map requires transform: (T) -> R (≈ KFunction1<T,R>) function

Child::doSomethingWithParent is KFunction2<Child, Parent, Foo> (≈ f: (Child, Parent) -> Foo). It's method reference therefore it requires an object on which the function will be invoked (Child parameter)

You can do something like this:

class Parent {
    val child: Child = Child()

    fun foo() = child.doSomethingWithParent(this)
}

val l1 = list.map(Parent::foo)

Upvotes: 3

gidds
gidds

Reputation: 18547

The clue is in the error messages.  (Which is why it's usually a good idea to give them in the question…)

In your line:

list.map(Child::doSomethingWithParent)

which child should do something with each the listed parent?  You're not specifying that it's the listed parent's child.

And in your line:

list.map(Parent::child::doSomethingWithParent)

what is the second :: supposed to indicate?  Parent::child is a method reference, not a class or object.

Upvotes: 2

Related Questions