Can one override a function with lambda expression?
I was following the koans Kotlin Playground: Edit, Run, Share Kotlin Code Online,
and below code
import java.util.*
fun getList(): List<Int> {
val arrayList = arrayListOf(1, 5, 2)
Collections.sort(arrayList, object : Comparator<Int> {
override fun compare = {x: Int, y: Int -> y - x}
})
return arrayList
}
gave me error messages:
Object is not abstract and does not implement abstract member public abstract fun compare(p0: Int!, p1: Int!): Int defined in java.util.Comparator
'compare' overrides nothing
Expecting '('
Can someone elaborate these messages?
EDIT:
additionally when I tried different codes in the line starting with override fun compare
,
1.
override fun compare(x: Int, y: Int) {
return y - x
}
this did not work as well, producing error messages
Return type of 'compare' is not a subtype of the return type of the overridden member 'public abstract fun compare(p0: Int!, p1: Int!): Int defined in java.util.Comparator'
Type mismatch: inferred type is Int but Unit was expected
I don’t understand the error message. Why was the expected type Unit
, not Int
? Shouldn’t the compiler expect the return type as Int
?
BUT
2. with a slight modification,
override fun compare(x: Int, y: Int): Int {
return y - x
}
this worked.
3.
override fun compare(x: Int, y: Int) = y - x
This works also. But in this case, I also didn’t explicitly write the return type, same as approach 1.
What are the differences between them? Why did 1. produce error while the other two didn’t? What’s happening under the hood?
EDIT 2:
I looked at the next koan Kotlin Playground: Edit, Run, Share Kotlin Code Online,
here indeed the lambda expression was used, but not with the object
expression.
import java.util.*
fun getList(): List<Int> {
val arrayList = arrayListOf(1, 5, 2)
Collections.sort(arrayList, { x, y -> y - x })
return arrayList
}
But then here, inside the lambda expression the types are not explicitly stated. Why would this work, compared to the other approaches above?