Skip to content

Instantly share code, notes, and snippets.

@jackywyz
Created August 22, 2011 09:41
Show Gist options
  • Save jackywyz/1162029 to your computer and use it in GitHub Desktop.
Save jackywyz/1162029 to your computer and use it in GitHub Desktop.
scala self-types and Structure-type
abstract class Ta{
def say(a:Int):Int =a+2
}
trait T{
def say(a:Int):Int = a
}
//有实体函数的trait T会编译成
abstract trait T$class extends {
def say($this: T, a: Int): Int = a;
def /*T$class*/$init$($this: T): Unit = {
()
}
};
object SelfTypes {
trait MustHave1
trait MustHave2
trait Independent
// constrain the traits A, B and C
trait A { self: MustHave1 => }
trait B { self: MustHave2 => }
trait C { self: MustHave1 with MustHave2 => }
// correct usage
class Test1 extends MustHave1 with A
class Test2 extends MustHave2 with B
class Test3 extends MustHave1 with MustHave2 with C
class Test4 extends MustHave1 with Independent with A
class Test5 extends Test1 with A
class Test6 extends Test3 with A with B
// -- these examples do not type check
// class Wrong1 extends A
// class Wrong2 extends A with Independent
// class Wrong3 extends MustHave2 with A
// class Wrong4 extends MustHave1 with C
// mixing the behaviours Resize and ColorCount in our domain Image
case class Image(width: Int, height: Int, buf: Array[Byte])
trait Resize { self: Image =>
def resize(newWidth: Int, newHeight: Int): Image = {
// a really stupid implementation
Image(newWidth, newHeight, buf.slice(0, newWidth * newHeight))
}
}
trait ColorCount { self: Image =>
def count(color: Byte) = buf.foldLeft(0) {(a, v) => if(v == color) a + 1 else a }
}
def main(args: Array[String]) = {
val i = new Image(5, 3, Array(1,2,2,2,2,1,3,3,3,3,1,2,2,2,2))
with Resize
with ColorCount
val n = i.resize(3, 1)
assert(n.width == 3)
assert(n.height == 1)
assert(n.buf.size == (n.width * n.height))
assert(i.count(1) == 3)
assert(i.count(2) == 8)
assert(i.count(3) == 4)
}
}
class Te{
def call:String = "Hello"
}
object Te{
def apply() = new Te()
def foo(callable: { def call: String }) = println(callable call)
def main(args:Array[String]){
this foo this()
}
}
@jackywyz
Copy link
Author

'''1 必须被掺入到Image类或其子类中
self :Image  =>:Image是可以省略的
''' 2 在当前trait中的可以调用self 

@jackywyz
Copy link
Author

''' 类型擦除
1)只知道是否是List类型,不知道是否Int,但是Array[Int]除外,因为Array的类型与元素是绑定的。
 def method(a:Any) =  a match { case a:List[Int] => ...}

2)Array的类型与元素是绑定的,不同的元素就是不同的类型。
def  method[T] (a:T) = new Array[T](3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment