How to specify typical types of ducks (implicit interface) in Kotlin?

for instance

// Not valid Kotlin code.
fun <T : Summable> myFunction ...

T : Summablemeans that any type Tsupports the operator +, i.e. has a method .plus.

+4
source share
2 answers

There is no such function in Kotlin, and at present it is not planned for a future release.

+3
source

You can take a look at the DucKtypes project on GitHub, which allows you to use "static ducktyping". For instance:

interface Summable { fun plus() }
object x { fun plus(){ println("plus") } } 
fun myFunction( s : Summable ){ s.plus() }
myFunction( x )

The project is still fairly new, but gradle -plugin may soon be launched to automate code generation.

+1
source

Source: https://habr.com/ru/post/1653160/


All Articles