Skip to content

Commit 3248d91

Browse files
Add self-type for Traits
1 parent 13aa90a commit 3248d91

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

src/main/scala/stdlib/Traits.scala

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,5 +100,24 @@ object Traits extends FlatSpec with Matchers with org.scalaexercises.definitions
100100
myListener.isInstanceOf[Any] should be(res2)
101101
myListener.isInstanceOf[AnyRef] should be(res3)
102102
}
103-
103+
104+
/** Traits also can use self-types. A self-type lists the required dependencies for mixing in the trait. When mixing in the main trait, all self-type dependencies of that trait must also be mixed in, otherwise a compile-time error is thrown.
105+
*
106+
* Also, the dependencies can't have identical method/property names or else you'll get an `illegal inheritance` error.
107+
*/
108+
def selfTypeTraits(res0: Int){
109+
trait B {
110+
def bId = 2
111+
}
112+
113+
trait A {
114+
self: B =>
115+
116+
def aId = 1
117+
}
118+
119+
//val a = new A //***does not compile!!!***
120+
val obj = new A with B
121+
(obj.aId + obj.bId) should be(res0)
122+
}
104123
}

0 commit comments

Comments
 (0)