Kotlin: Interface … does not have constructors

前端 未结 7 1169
长情又很酷
长情又很酷 2020-12-04 16:14

I am converting some of my Java code to Kotlin and I do not quite understand how to instantiate interfaces that are defined in Kotlin code. As an example, I have an interfac

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 16:32

    SAM conversion is supported for interfaces defined in Kotlin since 1.4.0

    What's New in Kotlin 1.4.0

    Before Kotlin 1.4.0, you could apply SAM (Single Abstract Method) conversions only when working with Java methods and Java interfaces from Kotlin. From now on, you can use SAM conversions for Kotlin interfaces as well. To do so, mark a Kotlin interface explicitly as functional with the fun modifier.

    SAM conversion applies if you pass a lambda as an argument when an interface with only one single abstract method is expected as a parameter. In this case, the compiler automatically converts the lambda to an instance of the class that implements the abstract member function.

    So the example in Your question will look something like this:

    fun interface MyInterface
    {
        fun onLocationMeasured(location: String)
    }
    
    fun main()
    {
        val myObj = MyInterface { println(it) }
    
        myObj.onLocationMeasured("New York")
    }
    

提交回复
热议问题