The normal way to use a trait is to mix it in to an object. However there can be a problem mixing two traits containing methods with equal signatures. If the two traits are not designed to work together then you will get a compile error. Otherwise one method will override the other. Either way you cannot access both methods. There is an additional way to access the functionality of a trait. You can create an object (not instance) that extends the trait and import the methods when you need them.
If the trait is stateless then the object can be shared if not then make sure that sharing the object is carefully handled.
Examples:
- scala> trait T1 {
- | def talk = "hi"
- | }
- defined trait T1
- scala> trait T2 {
- | def talk = "hello"
- | }
- defined trait T2
- // Cannot extend C with T1 and T2 because they are not designed to work together
- scala> class C extends T1 with T2
:6: error: error overriding method talk in trait T1 of type => java.lang.String; - method talk in trait T2 of type => java.lang.String needs override modifier
- class C extends T1 with T2
- ^
- scala> class C extends T1
- defined class C
- // objects can have state so becareful how you share them
- scala> object Obj1 extends T1
- defined module Obj1
- scala> object Obj2 extends T2
- defined module Obj2
- // You can give aliases to the imported methods and use them in the class
- scala> class C {
- | import Obj1.{talk => hi}
- | import Obj2.{talk => hello}
- | def sayHi = hi
- | def sayHello = hello
- | }
- defined class C
- scala> val c = new C
- c: C = C@54d8fd1a
- scala> c.sayHi
- res0: java.lang.String = hi
- scala> c.sayHello
- res1: java.lang.String = hello
- scala> class C extends T1 {
- | import Obj2.{talk => hello}
- | def helloTalk = hello
- | }
- defined class C
- scala> val c2 = new C
- c2: C = C@2ee634bf
- scala> c2.talk
- res2: java.lang.String = hi
- scala> c2.helloTalk
- res5: java.lang.String = hello
No comments:
Post a Comment