I have this code:
package org.medianik.kotlindoc
fun main(){
val creator:Creatable = toCreatable(::Created)// Ok. Compiles, and works fine
val creator1:Creatable = ::Created // Compilation error
val creator2:Creatable = ::Created as Creatable // ok enough to compile, but there is runtime exception
val c = creator.create(5)
val creator3:Creatable = toCreatable(c::doSmth1) // Ok. Compiles, works fine
val creator4:Creatable = c::doSmth1 // Compilation error
val creator5:Creatable = c::doSmth1 as Creatable // Again ok enough to compile, but there is runtime exception
val creator6:Creatable = Creatable { i -> Created(i) } // Works fine, but that's not what I want
}
fun toCreatable(c:Creatable) = c
fun interface Creatable{
fun create(i: Int) : Created
}
class Created(private var i: Int){
fun doSmth1(add: Int): Created{
return this.also { i+=add }
}
}
Exception for creator2:
Exception in thread "main" java.lang.ClassCastException: class org.medianik.kotlindoc.MainKt$main$creator2$1 cannot be cast to class org.medianik.kotlindoc.Creatable (org.medianik.kotlindoc.MainKt$main$creator2$1 and org.medianik.kotlindoc.Creatable are in unnamed module of loader 'app')
Exception for creator5:
Exception in thread "main" java.lang.ClassCastException: class org.medianik.kotlindoc.MainKt$main$creator5$1 cannot be cast to class org.medianik.kotlindoc.Creatable (org.medianik.kotlindoc.MainKt$main$creator5$1 and org.medianik.kotlindoc.Creatable are in unnamed module of loader 'app')
I have no idea how to make creator1/4 work with method reference. Is there any ways to make them work? Because it seems senseless to me: if you pass method reference to a function as an argument -- it converts to interface, otherwise not. How does it work?
Are there some special casts for functions to interfaces?