scala(13)A Tour of Scala: Explicitly Typed Self References

本文深入探讨Scala编程中的类型推断机制,通过实例展示了如何使用初始表达式推断变量类型,并强调了类型推断在递归方法中的局限性。同时,文章还介绍了Scala中统一类型的概念,以及如何利用泛型实现类型安全的代码。最后,通过代码实例阐述了Stack类的使用,展示Scala中类型参数的灵活性。
scala(13)A Tour of Scala: Explicitly Typed Self References

Explicitly Typed Self References
…snip…

Subclassing
class Point(xc: Int, yc: Int){
val x: Int = xc
val y: Int = yc
def move(dx: Int, dy: Int): Point =
new Point(x+dx, y+ dy)
}

class ColorPoint(u: Int, v: Int, c: String) extends Point(u, v) {
val color: String = c
def compareWith(pt: ColorPoint) : Boolean =
(px.x == x) && (pt.y == y) && (pt.color == color)
override def move(dx: Int, dy: Int) : ColorPoint =
new ColorPoint(x + dy, y + dy, color)
}

Local Type Inference
Deduce the type from the initialization expression of the variable and return response of the return type.
def main(args: Array[String]): Unit = {
valx = 1 + 2 * 3// the type is Int
def succ(x: Int) :Int = x+ 1// the return type should be :Int and we can ommit it


}

And remember the recursive methods can not deduce the type of return.

Unified Types
All the values are objects in scala.

Variance
package com.sillycat.easyscala.start.tour.tour4

object VariancesTest extends App {
vars: Stack[Any] = new Stack().push("hello");
s = s.push(new Object())
s = s.push(7)
Console.println(s) //7 java.lang.Object@5b6df84b hello
}

class Stack[+A] {
def push[B >: A](elem: B): Stack[B] = new Stack[B] {
overridedef top: B = elem
overridedef pop: Stack[B] = Stack.this
overridedef toString() = elem.toString() + " " +
Stack.this.toString()
}
def top: A = sys.error("no element on stack")
def pop: Stack[A] = sys.error("no element on stack")
overridedef toString() = ""

}

Views
…snip…

XML Processing
…snip...

References:
http://www.scala-lang.org/node/104
http://www.scala-lang.org/node/124
http://www.scala-lang.org/node/125
http://www.scala-lang.org/node/127
http://www.scala-lang.org/node/128
http://www.scala-lang.org/node/130
http://www.scala-lang.org/node/131

scala(12) http://sillycat.iteye.com/blog/1842158
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值