Scala少用相同类型的参数键入

时间:2015-10-05 07:35:15

标签: scala

在GoLang中,如果函数接受多个相同类型的参数,则可以将其键入:

add := func(x, y int) int {
  return x + y
}

其中xy都属于int类型。

但是我无法知道scala是否存在这样的速记符号。我试过跟进,但没有用。

> def add(x, y: Int): Int = { x + y} 

error: ':' expected but ',' found.

对于一个简单的案例,它并没有太大的负担。但是对于我提出的一些案例,这看起来非常冗长,与斯卡拉在冗长问题上的立场相矛盾。

是否有这样的scala功能或语法糖,如果有我可以使用它?

2 个答案:

答案 0 :(得分:3)

在Scala中,使用*作为后缀,以表示此类型的值序列,例如

def add(x: Int*): Int = x.sum
add: (x: Int*)Int

等等

scala> add(1,2,3)
res0: Int = 6

现在x: Int*是一系列Int值,请考虑

def addMeta(x: Int*): Int = x.length
addMeta: (x: Int*)Int

scala> addMeta(0,1,2,3)
res1: Int = 4

答案 1 :(得分:3)

不,scala没有这个确切的功能。

实际上,有时候函数/类签名会变得非常长,特别是在为spray.json定义类似案例或者光滑时。

在这种情况下,我为常用类型使用type别名找到了可容忍的提示。

object TypeShortcuts {
  type I = Int
  type L = Long
  type S = String
  type D = Double
  type B = Boolean
  type O[T] = Option[T]
}

import TypeShortcuts._

然后这个讨厌的长声明:

case class Country(id: Int, currencyId: Option[Int], latin2: String, latin3: String, digital: String, names: Names, phoneCode: String)

我可以重写为更可忍受(更重要的是 - 简洁):

case class Country(id: I, currencyId: O[I], latin2: S, latin3: S, digital: S, names: Names, phoneCode: S)

这在某些角落的情况下特别方便,如同:),只想象全名版本的恐怖:

def applyOpt(t: (O[I], O[I], O[I], O[S], O[S], O[S], O[S], O[S], O[S], O[S], O[S], O[S], O[S], O[S], O[S], O[S])): O[BankInfo]