【问题标题】:Use case and examples for type pattern with type variable具有类型变量的类型模式的用例和示例
【发布时间】:2017-05-03 08:40:09
【问题描述】:

我发现在进行类型模式匹配时阅读了 scala 支持绑定类型变量的规范:

Map(1 -> "one", 2 -> "two") match {
  case l: Map[k, v] =>
    // binds k to Int and v to String
    // k and v are types as shown here:
    val i: Iterator[Tuple2[k, v]] = l.iterator
    println(i.mkString(", "))
}

我可以用它做一些花哨或实用的事情吗?或者绑定类型变量只对类型文档有用?

突然想到Scala有时需要类型注解,比如定义函数,所以我尝试了:

def prepender(obj: Any) = obj match {
  case xs: List[a] => (x: a) => x :: xs
  case opt: Some[a] => (x: a) => x :: Nil
}

但是返回函数的类型很奇怪:

prepender: (obj: Any)a with a => List[Any] forSome { type a; type a }

scala> val p = prepender(List(1,2))
p: a with a => List[Any] forSome { type a; type a } = <function1>

scala> p(1)
<console>:10: error: type mismatch;
 found   : Int(1)
 required: a(in value res7) with (some other)a(in value res7) where 
   type (some other)a(in value res7), type a(in value res7)

【问题讨论】:

  • 起初我认为这只是为了方便语法,因为类型在编译时总是已知的。但现在我想知道这是否可以用于实例化存在类型?

标签: scala types pattern-matching


【解决方案1】:

我希望这不会太长,但我严重怀疑它,这就是为什么我要先提供一个快速的答案:“当你命名(抽象)某事物时,主要用例是指它之后”。好吧,那现在没用了,是吗?

考虑这个简单的 Scala 函数:

val sum = (a: Int, b: Int) => a + b

编译器不需要知道aabb。它只需要知道ab 的类型为Int 并且ab 之前(在这种情况下这无关紧要,因为加法是可交换的,但编译器无论如何都会关心!)。 Scala 提供了一种(别误会我也喜欢它)编译器友好的占位符语法,它可以作为这个“假设”的证明。

val sum: (Int, Int) => Int = _ + _ // where the 1st _ differs from the 2nd _

现在看看这个:

case x: SomeTypeParameterizedWith[AnotherType] // AnotherType is erased anyway
case x: SomeParameterizedType[_] // Existential type
case x: SomeParameterizedType[kind] // Existential type which you can reference

当您不关心类型参数时,请使用占位符语法。当您(无论出于何种原因)关心时,您应该使用小写字母命名类型参数,以便编译器知道您要将其视为标识符。

回到你的问题。

存在类型的主要用途是处理 Java 的通配符类型。 这取自Programming in Scala - Existential Types,并由您的真实修改。

// This is a Java class with wildcards
public class Wild {
  public java.util.Collection<?> contents() {
    java.util.Collection<String> stuff = new Vector<String>();
    stuff.add("a");
    stuff.add("b");
    stuff.add("see");
    return stuff;
  }
}

// This is the problem
import scala.collection.mutable.Set
val iter = (new Wild).contents.iterator
val set = Set.empty[???] // what type goes here?
while (iter.hasMore)
  set += iter.next()

// This is the solution
def javaSet2ScalaSet[T](jset: java.util.Collection[T]): Set[T] = {
  val sset = Set.empty[T] // now T can be named!
  val iter = jset.iterator
  while (iter.hasNext)
    sset += iter.next()
  sset
}

好的,刚刚发生了什么?简单的泛型,没有魔法吗?!如果您每天都在处理泛型,这对您来说看起来很正常,但是您忘记了,将类型参数引入作用域的超超概念仅适用于类和方法。如果你在一个类或一个方法之外,只是在某个不知名的随机范围内(比如 REPL)怎么办?或者如果你在一个类或一个方法中,但是类型参数没有被引入到它们的作用域中怎么办?这就是你的问题和这个答案发挥作用的地方。

val set = new Wild().contents match {
  case jset: java.util.Collection[kind] => {
    val sset = Set.empty[kind]
    val iter = jset.iterator
    while (iter.hasNext)
      sset += iter.next()
    sset
  }
}

标识符kind 是必需的,以便编译器可以验证您指的是同一事物。

请注意,您不能只将字符串添加到set,因为set 的类型是Set[_]

【讨论】:

  • 只要你有时间,你能提供一些关于它如何工作的代码吗?
  • 给你。我希望它有所帮助。
  • val sset = Set.empty[kind] 更改为 val sset = Set.empty[Any] 并且您不需要任何类型模式。
猜你喜欢
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 2014-09-01
  • 2012-08-30
  • 2021-03-16
相关资源
最近更新 更多