【发布时间】:2019-03-14 00:43:57
【问题描述】:
我需要编写可以根据返回类型创建对象的方法。返回类型将是编译时已知的少数类型之一(尽管我很乐意接受运行时解决方案)。
如果重要的话,类型是数字而不是原始类型,例如半精度浮点数,并且不会全部继承自 Number (或类似的)。 (我可以创建一个描述一组特定子类型的基本类型吗?)
我需要类似的东西
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
}
}
我不知道怎么做
- 向编译器解释我知道 T 将是什么类型。
- 返回适当的实现
我见过的运行时解决方案,基于 TypeTags 或使用 match,需要一个输入参数来携带我在这种情况下没有的类型信息。
【问题讨论】:
-
抱歉新手问题,但这个问题发生了什么?之前有一个答案,好像被删了。我并不完全同意它,但它提供了一个不同的解决方案(我没有想到这可能在其他情况下也有效)。我已经发布了一个答案(对我有用),但已经被否决了两次,没有任何解释!