[英]Nil:List[Int] as parameter
我有以下特質定義:
sealed trait List[+A]
// `List` data type, parameterized on a type, `A`
case object Nil extends List[Nothing]
// A `List` data constructor representing the empty list
/* Another data constructor, representing nonempty lists. Note that `tail` is another `List[A]`,
which may be `Nil` or another `Cons`.
*/
case class Cons[+A](head: A, tail: List[A]) extends List[A]
和功能:
def add1(l: List[Int]): List[Int] =
foldRight(l, Nil:List[Int])((h,t) => Cons(h+1,t))
我的問題是, Nil:List[Int]
是什么意思? 這是不是意味着,我傳遞一個帶有Int
表示法的類型的Nil
列表?
由於fold
(及其變體)是根據第一個參數列表確定類型參數,因此您不能簡單地傳遞Nil
,因為類型將被導出為List[Nothing]
(您還會看到第二個參數列表不匹配)。 您可以使用類型歸屬來告訴Nil
是List[Int]
類型。 您還可以將List[Int]
作為類型參數傳遞:
foldRight[List[Int]](l, Nil)((h,t) => Cons(h+1,t))
作為參考, foldRight
簽名是這樣的:
def foldRight[B](z: B)(op: (A, B) => B): B
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.