30.scala编程思想笔记——参数化类型
欢迎转载,转载请标明出处:blog.csdn.net/notbaron/ar…
源码下载连接请见第一篇笔记。\
尽量让Scala完成推断类型是一个不错的主意,这样会使代码变得更整洁且更易于阅读。有时候无法识别出是什么类型,因此必须提供帮助。
例如:
import com.atomicscala.AtomicTest._
// Type is inferred:
val v1 = Vector(1,2,3)
val v2 = Vector("one", "two","three")
// Exactly the same, but explicitly typed:
val p1:Vector[Int] = Vector(1,2,3)
val p2:Vector[String] =
Vector("one", "two", "three")
v1 is p1
v2 is p2
其中Vector[Int]中的方括号表示类型参数。可以把Vector[Int]读作Int的向量。
类型参数对于容器之外的其他元素来说也非常有用。
返回类型也可以具有参数,如下:
import com.atomicscala.AtomicTest._
// Return type is inferred:
def inferred(c1:Char, c2:Char, c3:Char)={
Vector(c1,c2, c3)
}
// Explicit return type:
def explicit(c1:Char, c2:Char, c3:Char):
Vector[Char]= {
Vector(c1,c2, c3)
}
inferred('a', 'b', 'c') is
"Vector(a, b, c)"
explicit('a', 'b', 'c') is
"Vector(a, b, c)"
当指定了方法的返回类型时候,Scala可以检查并强化意图。