Scala:结合两个方法,一个返回List,另一个使用Generics将Set转换为一个方法

时间:2013-11-28 15:56:58

标签: scala scala-collections

Noob在这里。如何创建可用于代替以下两种方法的单一方法?

 def makeListSavingsAccounts( numSavAccts: Int ): List[ SavingsAccount] = {
    var saList: List[ BankAccount ] = List.empty 
    for ( saIDX <- 1 to numSavAccts ) saList :+= new SavingsAccount( 5000 )
    saList
  } 



  def makeSetSavingsAccounts( numSavAccts: Int ): Set[ SavingsAccount] = {
    var saSet: Set[ BankAccount ] = Set.empty 
    for ( saIDX <- 1 to numSavAccts ) saSet += new SavingsAccount( 5000 )
    saSet
  }   

像????

  def makeCollectionSavingsAccounts[T <: ???[ SavingsAccount ]] ( numSavAccts:Int ): T = {
    var saColl: T = ???.empty 

    for ( saIDX <- 1 to numSavAccts ) saColl  ?????? new SavingsAccount( 5000 )
    saColl
  }

我们感谢您分享您的Scala知识......

2 个答案:

答案 0 :(得分:3)

没有任何神奇的东西,比如can-build-from和builders:

def makeListSavingsAccounts(accsNum: Int ): List[ SavingsAccount] = {
    val accs = for (saIDX <- 1 to accsNum) yield new SavingsAccount( 5000)
    accs.toList
}

def makeSetSavingsAccounts(accsNum: Int): Set[SavingsAccount] = 
    makeListSavingsAccounts(accsNum).toSet

P.S。 makeListSavingsAccounts的替代实施是List.fill(accsNum)(new SavingsAccount( 5000))

答案 1 :(得分:3)

这是遵循Scala集合库的方式。所以我相信以下方式是原生的。

scala> def makeSavingAccounts[T[_]](count:Int)(implicit cbf: scala.collection.generic.CanBuildFrom[T[_], BankAccount, T[BankAccount]]) = {
        val builder = cbf()
        builder.sizeHint(count)
        for(i <- 1 to count) builder += SavingsAccount(5000)
        builder.result
      }

scala> makeSavingAccounts[List](3)
res0: List[BankAccount] = List(SavingsAccount(5000), SavingsAccount(5000), SavingsAccount(5000))

scala> makeSavingAccounts[Set](3)
res2: Set[BankAccount] = Set(SavingsAccount(5000))