标签:style http color io os 使用 java ar art
鸭子类型:“当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子。”
一般在动态语言里面才有,因为静态语言是强类型的,会在编译期检查类型,很难实现。但是Scala作为一门static type语言,居然支持,不得不说Scala确实很强大。直接上code
package testscala object StructuralTyping extends App { def quacker(duck: {def quack(value: String): String}) { println(duck.quack("Quack")) } object BigDuck { def quack(value: String) = { value.toUpperCase } } object SmallDuck { def quack(value: String) = { value.toLowerCase } } object IamNotReallyADuck { def quack(value: String) = { "prrrrrp" } } quacker(BigDuck) quacker(SmallDuck) quacker(IamNotReallyADuck) // object NoQuaker { // } // // quacker(NoQuaker) // 编译错误!!!! val x = new AnyRef { def quack(value: String) = { "No type needed " + value } } quacker(x) }
Ref
1. http://en.wikibooks.org/wiki/Scala/Structural_Typing
2. http://java.dzone.com/articles/duck-typing-scala-structural
3. http://www.draconianoverlord.com/2011/10/04/why-no-one-uses-scala-structural-typing.html
标签:style http color io os 使用 java ar art
原文地址:http://my.oschina.net/magicly007/blog/313863