Scala Parameterized Types

原创转载请注明出处:http://agilestyle.iteye.com/blog/2333316

参数化类型

We consider it a good idea to let Scala infer types whenever possible. It tends to make the code cleaner and easier to read. Sometimes, however, Scala can’t figure out what type to use (it complains), so we must help. For example, we must occasionally tell Scala the type contained in a Vector. Often, Scala can figure this out:

package org.fool.scala.parameterizedtypes

object ParameterizedTypes extends App {
  // Type is inferred:
  val v1 = Vector(1, 2, 3)
  val v2 = Vector("one", "two", "three")

  println(v1)
  println(v2)

  // Exactly the same, but explicitly typed:
  val p1: Vector[Int] = Vector(1, 2, 3)
  val p2: Vector[String] = Vector("One", "Two", "Three")

  println(p1)
  println(p2)

  // 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)

  println(inferred('a', 'b', 'c'))
  println(explicit('a', 'b', 'c'))
}

Note:

类型声明Vector[Int],方括号表示类型参数

Console Output


 

猜你喜欢

转载自agilestyle.iteye.com/blog/2333316