Method references: supplying arguments and/or chaining

For method references, is there any way to specify arguments, like:

val set = hashSetOf<String>()
val s = "abc"
methodAcceptingSupplierOfBoolean(set::add(s))

Also, is it possible to chain calls after a method reference? e.g., is it possible to:

val l = LinkedList<Number>()

… populate l …

methodWithSupplierOfStringParameter(l::removeFirst.toString())

Also, is it possible to chain method references? e.g.:

val l = LinkedList<Number>()

… populate l …

methodWithSupplierOfSupplierOfStringParameter(l::removeFirst::toString)

Basically, :: specifies something that can be called later, whereas . just immediately performs the call.

Pretty sure that is what lambdas are for.

2 Likes

Yeah, but there shouldn’t be any need for method references at all, since lambdas are supported. I also think that being able to use :: anywhere would be useful, rather than just at a single first level for a method reference.

No, because method references are just that: references to existing methods/functions. If the function you want to supply doesn’t take any argument, then you’re not referencing set.add anymore, because that one does require an argument.

You should be explicit about this by using a lambda:

methodAcceptingSupplierOfBoolean { set.add(s) }

Why would you want to use method references here if you want to perform a completely different operation? A lambda is also really appropriate here:

methodAcceptingSupplierOfBoolean { l.removeFirst.toString() }

If I understood correctly, your method here expects a () -> () -> String, is that right?

Now the proposed syntax is not clear, should we expect this to be interpreted as:

methodWithSupplierOfSupplierOfStringParameter { { l.removeFirst().toString() } }

Or:

methodWithSupplierOfSupplierOfStringParameter {
    val first = l.removeFirst();
    { first.toString() }
}

In the first case, I don’t see any improvements over the lambda.

In the second case, it could be useful indeed, although I haven’t so far run into any real-life situation where I needed this. However, I believe we’re getting away of the initial meaning of “method reference” here. We’re not passing a reference to a method here, but instead using that syntax as a short-hand for lambda creation, and I’m not a fan of hacking the meaning of the operator this way.