2011-01-28 41 views
10

Tôi muốn tạo một đặc điểm thêm một số thuộc tính vào một lớp và làm cho nó có thể thành các phương thức chuỗi. Thử nghiệm trong Scala 2.8.1.Thực tiễn tốt nhất để thực hiện đặc điểm Scala hỗ trợ phương pháp chuỗi

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() 

Thực tiễn phổ biến nhất trong loại tình huống này là gì? (Ưu tiên loại an toàn hơn)

Trả lời

20

Bạn có thể chỉ định rõ ràng loại cá thể làm kiểu trả về cho setProp.

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

Điều này là tốt. – lscoughlin

+0

Nó hoạt động! Nhưng tôi không hiểu tại sao. Tôi đoán 'this.type' bằng 'SomeProperty', phải không? Scala này có cụ thể không? Hoặc cũng có thể trong Java? – ihji

+0

Bài viết này hữu ích. http://scalada.blogspot.com/2008/02/thistype-for-chaining-method-calls.html – ihji

0

Điều dễ nhất cần làm là sử dụng chung chung.

object Value { 

    trait SomeProperty[X] { 
    var str: String = null; 
    def setStr(s: String): X = { 
     str = s; 
     return this.asInstanceOf[X] 
    } 
    } 

    abstract sealed class Value 
    case class IntegerValue(i: Int) 
    case class StringValue(s: String) extends SomeProperty[StringValue] { 
    def foo(): Unit = { 
     println("Foo.") 
    } 
    } 
    case class UnknownValue(o: Any) extends SomeProperty[UnknownValue] { 
    def bar(): Unit = { 
     println("Bar.") 
    } 
    } 

    def main(args: Array[String]): Unit = { 

    new UnknownValue(18).setStr("blah blah blah").bar 
    new StringValue("A").setStr("halb halb halb").foo 
    } 
} 
1

Không chắc nếu đây là những gì bạn đang tìm kiếm

scala> trait Property[T] { 
    | me: T => 
    | var prop:String="" 
    | def setProp(s:String) = { 
    |  prop=s 
    |  me 
    | } 
    | } 
defined trait Property 

scala> class A extends Property[A] 
defined class A 

scala> class B extends Property[B] 
defined class B 

scala> val a= new A 
a: A = [email protected] 

scala> val b = new B 
b: B = [email protected] 

scala> a.setProp("Hi") 
res13: Property[A] with A = [email protected] 

scala> a.setProp("Hi").setProp("Bye") 
res14: Property[A] with A = [email protected] 

scala> b.setProp("D") 
res15: Property[B] with B = [email protected] 
Các vấn đề liên quan