3

I came across this

private final Function1<byte[], Boolean> successConditionForResponse;

and wonder how to compare two of this in Java or Kotlin?

I search but cant really find specifically

Tord Larsen
  • 2,670
  • 8
  • 33
  • 76

2 Answers2

2

Well, what do you want this comparison to do? equals on functions will check whether they are the same object, because it doesn't override the default implementation (so will ==, but you don't want to get into habit of using it for objects in Java). So if that's what you want, you are done.

If you want to check that two functions are equal semantically (that is, they give the same result and have the same side effects when invoked on any arguments), there's no way to do it and there really can't be for well-known mathematical reasons.

Finally, you may want to know whether they are created by the same lambda and capture the same values. This should be possible to do for Kotlin lambdas by serializing them and comparing results, for Java lambdas you need to create them in a specific way. This is kind of a hack and slow, but may be good enough.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
-1

Case 1.
Let's say you have:

val a: (ByteArray) -> Boolean = ...
val b: (ByteArray) -> Boolean = ...

In this case you have two Kotlin functions assigned to two vals.
If you want to compare the results of the two functions on a given argument, you can do:

if(a(someByteArray) == b(someByteArray))

Instead, if you truly want to compare the two functions, you can simply do:

if(a == b)

Case 2.
Let's say you have:

val a: Function1<ByteArray, Boolean> = ...
val b: Function1<ByteArray, Boolean> = ...

In this case you don't have two Kotlin functions, but two objects of type Function1<T, R>.

Similarly to the previous case:

Comparing the results of the functions:

if (a.apply(someByteArray) == b.apply(someByteArray))

Comparing the two objects of type Function1<ByteArray, Boolean>:

if(a == b)
gpunto
  • 2,573
  • 1
  • 14
  • 17
  • Thanks , I saw this code from Kotlin `Intrinsics.areEqual(successConditionForResponse1, successConditionForResponse2)` , how does that compare? – Tord Larsen Mar 15 '19 at 17:18
  • That is simply a static method that checks equality. You can find the implementation here: https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/jvm/runtime/kotlin/jvm/internal/Intrinsics.java – gpunto Mar 15 '19 at 17:23