转换Scala中的类型

时间:2012-08-24 00:19:31

标签: scala type-conversion

Scala转换的最佳方式是什么:

选项[INT]

为:

选项[龙]

1 个答案:

答案 0 :(得分:5)

这正是map的用途:

def convert(x: Option[Int]) = x map (_.toLong)

其中的工作原理如下:

scala> convert(Some(1))
res0: Option[Long] = Some(1)

scala> convert(None)
res1: Option[Long] = None

scala.Predef提供从IntRichInt的隐式转换,这是toLong方法的来源。