有没有办法要求构造者采取特定的参数?

时间:2016-12-15 21:49:15

标签: scala

我认为我想做的事情很简单,但我没有得到正确的搜索字词集合。我想要的是一个特性,它保证所有实现类都有一个可以用已知类型的对象调用的构造函数。语法应该是:

trait Message {
  def this(rdr: msgpack.MsgReader): Message
}

但编译器告诉我它需要一个等号。知道怎么做吗?

1 个答案:

答案 0 :(得分:1)

改为使用类型类模式:

trait Message[T] {
  def read(reader: msgpack.MsgReader): T
  // Example of what would be a normal instance method.
  // thiz is similar to this, except because we're in another object it must be explicitly taken as parameter.
  // It's in a separate param list for convention and ease of currying
  def foo(thiz: T)(param1: Int): Boolean
}

// "Implementors" don't actually implement it, the behavior exists as its own singleton
class Foo { ... }

implicit object FooMessage extends Message[Foo] {
  // Note that this is not restricted to just constructors. If you want that then you are really out of luck. (And probably doing it wrong.)
  override def read(reader: msgpack.MsgReader) = ???
  override def foo(thiz: Foo)(param1: Int) = thiz.foo(param1)
}

// Usage
// Use an explicit, named implicit param to avoid implicitly
def readMsg[T: Message](reader: msgpack.MsgReader) = implicitly[Message[T]].read(reader)

val foo = readMsg[Foo](???)