实现支持方法链的 Scala 特征的最佳实践 [英] Best practice to implement Scala trait which supports method chaining

查看:60
本文介绍了实现支持方法链的 Scala 特征的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to make a trait which add some property to a class and make it possible to chain methods. Tested in 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 of SomeProperty
   x.setProp("test").bar()

在这种情况下最常见的做法是什么?(类型安全的方式是首选)

What is the most common practice in this kind of situation? (Type-safe way is preferred)

推荐答案

您可以明确指定实例类型作为 setProp 的返回类型.

You can explicitly specify the instance type as the return type for setProp.

trait SomeProperty {
    var prop : String = "default"
    def setProp(s: String):this.type = {
        prop = s
        this
    }
}

这篇关于实现支持方法链的 Scala 特征的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆