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


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值