0

In Scala I can write:

val x: Serializable with Runnable = ???

How can I do the same in Kotlin and Java?

caeus
  • 3,084
  • 1
  • 22
  • 36
  • You can't do that in Java and it's not a possible scenario. In Java, any instances you create have a known type. You cannot create anonymous class instance that has multiple super types like `new A with B {}`. You have to create a concrete class/interface and then instantiate it, like `interface C extends A, B {}`. Therefore you won't have the scenario that requires you to declare a variable with A with B type because that would be just C – SwiftMango Mar 01 '22 at 05:52

1 Answers1

-2

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
}
Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26