How to compare two kotlin.jvm.functions in java

问题: 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...

问题:

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


回答1:

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.


回答2:

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)
  • 发表于 2019-03-18 09:28
  • 阅读 ( 188 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除