2

Please note: Even though this question specifically addresses Netflix' Hystrix library, this is definitely a pure Groovy/JVM generics question at heart. Any battle-weary Java/Groovy veteran should be able to answer this, regardless of their knowledge/experience with Hystrix.


I want to build an abstract base HystrixCommand to return Guava Optionals as their generic RESULT type:

import com.google.common.base.Optional
import com.netflix.hystrix.HystrixCommand

abstract class BaseHystrixCommand<Optional<RESULT>> extends HystrixCommand {
    // My code here...
}

However this code produces the following compiler error:

Groovy:unexpected token: < @ line 23, column 42.

Line 23 column 42 is the inner opening angle bracket for RESULT:

...BaseHystrixCommand<Optional<RESULT...
                              ^ right here

Using Java 8, Groovy 2.4.3, Hystrix 1.4.18 and Guava 18.0 here. Any ideas what is causing this compiler error?

smeeb
  • 27,777
  • 57
  • 250
  • 447

1 Answers1

3

You can't use intermediate types in your type parameters, you just declare the type parameters directly and then use a parameterized Optional as a method parameter or return type:

abstract class BaseHystrixCommand<T> extends HystrixCommand {
    Optional<T> someMethod();
}

You can also create a second, bound type parameter based on the first (though the example here is stupid, you wouldn't extend Optional), but you would need to specify its concrete type at instanciation:

abstract class BaseHystrixCommand<T, U extends Optional<T>> extends HystrixCommand {
    U someMethod();
}

UPDATE

HystrixCommand is actually a parameterized class, and you want to make its parameterized methods (such as run()) return an Optional. Just parameterize the HystrixCommand correctly in the subclass:

abstract class BaseHystrixCommand<T> extends HystrixCommand<Optional<T>> {
    // ...
}

Of course, all methods returning the parameterized type will now return an Optional, it stays consistent with the original declaration.

Side note: you really want to use single letters for parameterized types, to avoid the confusion with constants and follow the style conventions.

Frank Pavageau
  • 11,477
  • 1
  • 43
  • 53
  • Thanks @Frank Pavageau (+1) - the problem is that by extending `HystrixCommand` I must override several methods, such as [`HystrixCommand#run`](https://netflix.github.io/Hystrix/javadoc/com/netflix/hystrix/HystrixCommand.html#run()). I want my `run()` override to return an `Optional`, **not** just a `RESULT`. Any ideas here? It sounds like my only course of action is to perhaps subclass `Optional` with a dummy wrapper and then use `BaseHystrixCommand>`? – smeeb Nov 03 '15 at 15:31
  • For instance, something like `class OptionalWrapper extends Optional { }`? – smeeb Nov 03 '15 at 15:32
  • I've edited my answer to address your additional question. – Frank Pavageau Nov 03 '15 at 22:31