2017-06-15 33 views
0

我有一個List[Int],我從輸入讀取。 我想將該清單的部分款項存入List[Long]獲取列表[Int]的部分總和到列表[長]

val a: List[Int] = readLine().split(" ").map(_.toInt).toList 
val sumList: List[Long] = a.scanLeft(0)(_.toLong + _.toLong).tail.toList 

不過,我得到這個錯誤:

Solution.scala:54: error: type mismatch; 
found : Long 
required: Int 
      val sumList: List[Long] = a.scanLeft(0)(_.toLong + _.toLong).tail.toList 
                  ^
Solution.scala:54: error: type mismatch; 
found : List[Int] 
required: List[Long] 
      val sumList: List[Long] = a.scanLeft(0)(_.toLong + _.toLong).tail.toList 
                      ^

任何想法,我究竟做錯了什麼?

回答

2

0應該是0L。大多數功能操作的「零值」似乎是類型推斷的基礎。

+0

在Scala中,輸入推理從左到右通過參數列表(但不在參數列表中)。因此,第二個參數列表中的類型是根據第一個參數列表推斷的,即「0L」。 –

2

爲什麼不將初始List a List[Long],因爲您正在投射Int s到Long

val a: List[Long] = readLine().split(" ").map(_.toLong).toList 
val sumList: List[Long] = a.scanLeft(0L)(_ + _).tail.toList