小编ihj*_*hji的帖子

实现支持方法链的Scala特征的最佳实践

我想创建一个特性,为类添加一些属性,并使链式方法成为可能.在Scala 2.8.1中测试过.

trait SomeProperty {
    var prop : String = "default"
    def setProp(s: String) = {
        prop = s
        this
    }
}
sealed abstract class Value
case class IntegerValue(v: Int) extends Value
case class FloatValue(v: Float) extends Value with SomeProperty {
    def foo() = { println("I'm foo.") }
}
case object UnknownValue extends Value with SomeProperty {
    def bar() = { println("I'm bar.") }
}

scala> val x = UnknownValue
scala> x.setProp("test").bar()
<console>:10: error: value bar is not a member …
Run Code Online (Sandbox Code Playgroud)

scala traits method-chaining

10
推荐指数
1
解决办法
3827
查看次数

标签 统计

method-chaining ×1

scala ×1

traits ×1