I need to write method that can create an object based on the return type. The return type will be one one of small number of types known at compile time (although I'll happily accept a run time solution).
If it matters, the types are numeric but not primitive types, e.g. a half precision float, and won't all inherit from Number (or similar). (Can I create a base type that delineates a specific set of subtypes?)
I need to something like
object Thing {
def apply[T](size: Int): Thing[T] = {
// The call to makeBuffer[T] is inside another generic.
// I know there are only a limited number types that T can be
// so I can implement them individually but the compiler does
// not know this so it fails to compile
val buffer = makeBuffer[T](size)
// more stuff including calling 3rd party generic APIs
// that depend on T
}
private def [T]makeBuffer(size: Int): Buffer[T] = {
// What do I put here to build and return the correct Buffer?
}
abstract class Buffer[T](size: Int) {
def doStuff
}
// I can implement the small number of concrete classes that I need
class FloatBuffer(size: Int) extends Buffer[T](size) {
override def doStuff = // Allocate a buffer with size bytes
}
}
I don't know how to
- explain to the compiler that I know what types T will be.
- return the appropriate implementation
Runtime solutions I've seen, based on TypeTags or using match, need an input argument to carry the type information which I don't have in this case.