124

Say I want a type variable, T, that extends a certain class and implements an interface. Something like:

class Foo <T : Bar implements Baz> { ... }

What is the syntax for this in Kotlin?

frenchdonuts
  • 1,342
  • 2
  • 8
  • 7

1 Answers1

252

Only one upper bound can be specified inside the angle brackets.

Kotlin offers different syntax for generic constraints when there is more than one constraint:

class Foo<T>(val t: T) where T : Bar, T : Baz { ... }

and for functions:

fun <T> f(): Foo where T : Bar, T : Baz { ... }

It is documented here.

hotkey
  • 140,743
  • 39
  • 371
  • 326
  • 4
    Is there any way to use it for parametr type of fun, for example, fun foo(arg : ClassType, InterfaceType){}? Without adding type parameter to class – Ufkoku Jan 28 '17 at 11:11
  • 1
    @Ufkoku, no, there's no way to do it: there's no intersection types in Kotlin, and generic parameters can only be declared explicitly. – hotkey Jan 28 '17 at 11:18
  • 1
    @hotkey I have a function below:```fun wrapClientListener(listener: RemoteController.OnClientUpdateListener): T where T : RemoteController.OnClientUpdateListener, T : NotificationListenerService```. I don't care of T's type. But When I call this method, Kotlin asks for the specific type. So how can i call this method? – leimenghao Aug 21 '20 at 10:11