Scala generic exception signature definition

I would like to use generics to determine which business exception is thrown by this method (the scala method will be called from Java, so it must be in the signature).

Here is how I would do it in Java:

public interface BaseInterface<T, E extends Throwable> { public T process(Class<E> wrapperExc) throws E; } public class ExcOne extends Exception {} public class SubclassOne implements BaseInterface<String, ExcOne> { @Override public String process(Class<ExcOne> wrapperExc) throws ExcOne { return null; } } 

Here I tried to execute Scala:

 class UsingGenerics[IN, OUT, E <: Throwable] { //@throws(classOf[E]) - error: class type required but E found def process(request: IN, wrapperExc: Class[E]): OUT = { null.asInstanceOf[OUT] } } 

and..

 trait BaseTrait { type Request type Response type BusinessException <: Throwable //error: class type required but BaseTrait.this.BusinessException found //@throws(classOf[BusinessException]) def process(request: Request): Response } class TraitImplementor extends BaseTrait { type Request = Input type Response = Output type BusinessException = BizExc def process(r: Request): Response = { if (1 != 2) throw new BusinessException("Bang") new Response } } class Input class Output class BizExc(msg: String) extends Exception(msg) 

Both commented lines in scala code will not compile.

I would appreciate it if someone could explain how to do this.

For me, "throw new BusinessException (" Bang ") indicates that an alias of type" BusinessException "is a compile-time literal, and therefore I expected it to work with classOf.

If it turns out that this is impossible, I would also like to get an idea of ​​what is happening with the type system or the order in which annotations are processed regarding type substitution.

+4
source share
1 answer

Actually, that would be the same in java for annotation. If you create an annotation

 public @interface Throwing { Class<? extends Throwable> exceptionType(); } 

you can throwing{exceptionType = RuntimeException.class} , but not throwing{exceptionType = E.class} . You cannot do E.class in java and classOf[E] in scala.

You cannot put a type parameter in an annotation. The problem is that scala @throws has an annotation and follows annotation rules, but the rule for throwing on the JVM is different. Maybe a special case will be justified.

+3
source

All Articles