原创转载请注明出处: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

Scala Parameterized Types
 

 

 

相关文章:

  • 2021-07-10
  • 2021-09-26
  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
  • 2021-05-25
猜你喜欢
  • 2022-12-23
  • 2021-12-12
  • 2022-01-17
  • 2021-09-28
  • 2021-06-08
  • 2021-12-29
相关资源
相似解决方案