Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify duck typing (implicit interface) generics in Kotlin?

Tags:

kotlin

For example

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

T : Summable means any type T supports + operator, i.e. has a .plus method defined.

like image 774
weakish Avatar asked Aug 31 '16 14:08

weakish


2 Answers

There is no such feature in Kotlin, and it's not planned for a future release at this time.

like image 174
yole Avatar answered Nov 11 '22 21:11

yole


You may want to take a look at the DucKtypes project at GitHub, which allows for "static ducktyping". For example:

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

The project is still pretty new, but might soon have a gradle-plugin to automate code-generation.

like image 20
stangls Avatar answered Nov 11 '22 23:11

stangls