加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 泛型类型的模式匹配

发布时间:2020-12-16 09:08:49 所属栏目:安全 来源:网络整理
导读:为什么我不能模式匹配Node [T]? object Visitor { def inorder[T](root: Node[T]) : Unit = { root match { case End = return; case Node[T] = { if( root.left != null ) inorder( root.left ) println( root.toString ); inorder( root.right ); } case
为什么我不能模式匹配Node [T]?

object Visitor {
  def inorder[T](root: Node[T]) : Unit = {
    root match {
    case End => return;
    case Node[T] => {
      if( root.left != null )
          inorder( root.left )

      println( root.toString );
      inorder( root.right );
    }
    case _ => return;
    }
  }
}

更新:

该代码是99 scala problems的逐字副本

我收到这个编译时错误:

BinaryTree.scala:25: '=>' expected but '[' found.
[error]         case Node[T] => {
[error]                  ^
[error] one error found

25号线指向该线

case Node[T] => {

解决方法

好吧,我通过解释器运行你的代码,我认为它与类型擦除没有任何关系.可能只是一些语法错误.试试这个:

object Visitor {
  def inorder[T](root: Node[T]): Unit = {
    root match {
    case End => return;
    case n:Node[_] => {
      if( root.left != null )
          inorder( root.left )

      println( root.toString );
      inorder( root.right );
    }
    case _ => return;
    }
  }
}

您需要指明将绑定到匹配项的变量名称,例如n:Node [T].这会给你一个关于类型擦除的警告,你可以使用n:Node [_]删除它.编译器可以根据root的类型推断root.left和root.right的类型,所以类型擦除在这里并没有真正发挥作用……

注意:我刚检查了规范,类型模式的语法是:

varid ':' TypePat
'_' ':' TypePat

如果您从编译器提供实际的错误消息,以及Node和End的定义,这将有所帮助,否则我们需要推断所有这些事情.

编辑:

假设您正在编译http://aperiodic.net/phil/scala/s-99/tree.scala,则代码中确实存在语法错误.使用n:节点[_].然后你会得到一些类型错误.这对我有用:

import binarytree._
object Visitor {
  def inorder[T](root: Tree[T]) : Unit = {
    root match {
    case End => return;
    case n:Node[_] => {
      if( n.left != null )
          inorder( n.left )
      println( n.toString );
      inorder( n.right );
    }
    case _ => return;
    }
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读