代わり型クラスのパターンを使用します。
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](???)
コンストラクタは、インタフェースの一部にすることはできません。 –
これは残念です。実装にいくつかの署名のメソッドを持つコンパニオンオブジェクトがあることを強制する方法はありますか? – teryret
コレクション階層からヒントを得て、すべてに強制的に 'コンパニオン:ファクトリ'メソッドを持たせることができますが、それを行うにはインスタンスを必要とします。しかし、一般的に、Scalaの型システムでは、コンパニオン型間を移動することはできません(IMOのように、実際には関係していません)。 – HTNW