Stepper
ケースクラスを次のように書きたいとします。
case class Stepper(step: Int) {def apply(x: Int) = x + step}
toString
素敵な実装が付属しています:
scala> Stepper(42).toString
res0: String = Stepper(42)
しかし、それは実際には関数ではありません:
scala> Some(2) map Stepper(2)
<console>:10: error: type mismatch;
found : Stepper
required: Int => ?
Some(2) map Stepper(2)
Function
回避策は、特性を実装することです...
case class Stepper(step: Int) extends (Int => Int) {def apply(x: Int) = x + step}
しかし、私はもう素敵な toString 実装を無料で手に入れることはできません:
scala> Stepper(42).toString
res2: java.lang.String = <function1>
次に、問題は、これら 2 つの世界の最高のものを手に入れることができるかということです。toString
無料で素敵な実装があり、 trait の実装がある解決策はありますかFunction
。言い換えれば、case class
最終的に構文糖が適用されるような方法で線形化を適用する方法はありますか?