'How to declare multiple bounds to type of variable?

In Scala I can write:

val x: Serializable with Runnable = ???

How can I do the same in Kotlin and Java?



Solution 1:[1]

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
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeroen Steenbeeke