How to declare multiple bounds to type of variable?

34 views Asked by At

In Scala I can write:

val x: Serializable with Runnable = ???

How can I do the same in Kotlin and Java?

1

There are 1 answers

0
Jeroen Steenbeeke On

I'm assuming this statement means you're defining a variable of an anonymous type that extends both Serializable and Runnable? If so the Java equivalent would be something along the lines of:

interface SerializableRunnable extends Serializable, Runnable {}

public void method() {

  SerializableRunnable x = ??? // Whatever you were going to write in your Scala example
}

If you're using Java 16 or higher you can move the interface definition to your method body:


public void method() {
  // Local interface
  interface SerializableRunnable extends Serializable, Runnable {}

  SerializableRunnable x = ??? // Whatever you were going to write in your Scala example
}