Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I limit generic type argument to be one of 2 unrelated classes?

Tags:

generics

scala

I'd like to be able to do something like this (won't actually work):

class A[T <: B | C]

... and expect this to be valid:

new A[B]
new A[C]

... and this to yield compiller error:

new A[D]

Is something like this possible?

like image 571
Eugene Loy Avatar asked Oct 11 '14 12:10

Eugene Loy


People also ask

Which one of the following construct is used to create generic classes or methods?

We use <T> to create a generic class, interface, and method. The T is replaced with the actual type when we use it.

How to define a generic class in Java?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

What is generic parameter in c#?

Generic became part of C# with version 2.0 of the language and the CLR, or Common Language Runtime. It has introduced the concept of type parameters, which allow you to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.


1 Answers

You could use implicits:

trait AArg[T]

class A[T](implicit e: AArg[T])

implicit val argB = new AArg[B] { }
implicit val argC = new AArg[C] { }

although this doesn't prevent someone from creating an implicit val of type AArg[D].

like image 107
Lee Avatar answered Sep 30 '22 03:09

Lee