[英]scala template function vs forSome
我正在嘗試存在類型。
我在玩一個期望序列的函數,其中該seq的元素都是相同的類型。 我有..
def bar[X](as: Seq[A[X]]) = true
哪里...
// parametised type to use in the question
trait A[T]
然后,我遇到了“ forSome”語法,發現我可以用它達到相同的約束。
我寫了以下內容以進行比較...
// useful types
trait A[T]
class AI extends A[Int]
class AS extends A[String]
// define two functions that both have the same constraint.
// ie the arg must be a Sequence with all elements of the same parameterised type
def foo(as: Seq[A[X]] forSome { type X }) = true
def bar[X](as: Seq[A[X]]) = true
// these compile because all the elements are the same type (AI)
foo(Seq(new AI, new AI))
bar(Seq(new AI, new AI))
// both these fail compilation as expected because
// the X param of X[A] is different (AS vs AI)
foo(Seq(new AI, new AS))
bar(Seq(new AI, new AS))
我想了解的是-我錯過了什么嗎? 一個簽名相對於另一個簽名有什么好處。
一個明顯的區別是編譯錯誤是不同的。
scala> foo(Seq(new AI, new AS))
<console>:12: error: type mismatch;
found : Seq[A[_ >: String with Int]]
required: Seq[A[X]] forSome { type X }
foo(Seq(new AI, new AS))
^
scala> bar(Seq(new AI, new AS))
<console>:12: error: no type parameters for method bar: (as: Seq[A[X]])Boolean e
xist so that it can be applied to arguments (Seq[A[_ >: String with Int]])
--- because ---
argument expression's type is not compatible with formal parameter type;
found : Seq[A[_ >: String with Int]]
required: Seq[A[?X]]
bar(Seq(new AI, new AS))
^
<console>:12: error: type mismatch;
found : Seq[A[_ >: String with Int]]
required: Seq[A[X]]
bar(Seq(new AI, new AS))
^
scala>
區別在於,在foo
您可能不會引用X
,而在bar
您可以:
// fails
def foo(as: Seq[A[X]] forSome { type X }) = Set.empty[X]
// btw the same:
def foo(as: Seq[A[_]]) = Set.empty[???] // <-- what would you put here?
// OK
def bar[X](as: Seq[A[X]]) = Set.empty[X]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.