Scala doesn't allow you to specify the constructor's signature in a type constraint (as e.g. C#).
However Scala does allow you to achieve something equivalent by using the type class pattern. This is more flexible, but requires writing a bit more boilerplate code.
First, define a trait
which will be an interface for creating a T
given an Int
.
trait Factory[T] {
def fromInt(i: Int): T
}
Then, define an implicit
instance for any type you want. Let's say you have some class Foo
with an appropriate constructor.
implicit val FooFactory = new Factory[Foo] {
def fromInt(i: Int) = new Foo(i)
}
Now, you can specify a context bound for the type parameter T
in the signature of Class1
:
class Class1[T : Factory] {
def method1(i: Int) = {
val instance = implicitly[Factory[T]].fromInt(i)
// ...
}
}
The constraint T : Factory
says that there must be an implicit Factory[T]
in scope. When you need to use the instance, you grab it from implicit scope using the implicitly
method.
Alternatively, you could specify the factory as an implicit parameter to the method that requires it.
class Class1[T] {
def method1(i: Int)(implicit factory: Factory[T]) = {
val instance = factory.fromInt(i)
// ...
}
}
This is more flexible than putting the constraint in the class signature, because it means you could have other methods on Class1
that don't require a Factory[T]
. In that case, the compiler will not enforce that there is a Factory[T]
unless you call one of the methods that requires it.
In response to your update (with the abstract creator
method), this is a perfectly reasonable way to do it, as long as you don't mind creating a subtype of Class1
for every T
. Also note that T
will need to be a concrete type at any point that you want to create an instance of Class1
, because you will need to provide a concrete implementation for the abstract method.
Consider trying to create an instance of Class1
inside another generic method. When using the type class pattern, you can extend the necessary type constraint to the type signature of that method, in order to make this compile:
def instantiateClass1[T : Factory] = new Class1[T]
If you don't need to do this, then you might not need the full power of the type class pattern.
T
is (effectivelyT <: Any
), so it can't allow you to call a method that's not defined for this type. I'm not sure if you'll be able to do it all given Scala is built on top the JVM, and due to type erasure what you're doing is impossible in Java. However, again, I'm not sure - hence the comment, not an answer.def method1(i: Int, creator: Int => T)
(with the same body asmethod1
in your edit). Just like your proposed solution, this says nothing about the class having a constructor taking anInt
, so your proposed solution does not answer your question as currently stated; if an answer like this is fine in your scenario (and in 90% of cases it is) you might want to correct your question.