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

Scala模式与Option [Any]混淆

发布时间:2020-12-16 09:45:50 所属栏目:安全 来源:网络整理
导读:我有以下Scala代码。 import scala.actors.Actorobject Alice extends Actor { this.start def act{ loop{ react { case "Hello" = sender ! "Hi" case i:Int = sender ! 0 } } }}object Test { def test = { (Alice !? (100,"Hello")) match { case i:Some[
我有以下Scala代码。

import scala.actors.Actor

object Alice extends Actor {
  this.start
  def act{
    loop{
      react {
        case "Hello" => sender ! "Hi"
        case i:Int => sender ! 0
      }
    }
  }
}
object Test {
  def test = {
    (Alice !? (100,"Hello")) match {
      case i:Some[Int] => println ("Int received "+i)
      case s:Some[String] => println ("String received "+s)
      case _ =>
    }
    (Alice !? (100,1)) match {
      case i:Some[Int] => println ("Int received "+i)
      case s:Some[String] => println ("String received "+s)
      case _ =>
    }
  }
}

做了Test.test,我得到的输出:

scala> Test.test
Int received Some(Hi)
Int received Some(0)

我期待产出

String received Some(Hi)
Int received Some(0)

什么是解释?

作为第二个问题,我得到如下的未经检查的警告:

C:scalac -unchecked a.scala
a.scala:17: warning: non variable type-argument Int in type pattern Some[Int] is unchecked since it is eliminated by erasure
      case i:Some[Int] => println ("Int received "+i)
             ^
a.scala:18: warning: non variable type-argument String in type pattern Some[String] is unchecked since it is eliminated by erasure
      case s:Some[String] => println ("String received "+s)
             ^
a.scala:22: warning: non variable type-argument Int in type pattern Some[Int] is unchecked since it is eliminated by erasure
      case i:Some[Int] => println ("Int received "+i)
             ^
a.scala:23: warning: non variable type-argument String in type pattern Some[String] is unchecked since it is eliminated by erasure
      case s:Some[String] => println ("String received "+s)
             ^
four warnings found

如何避免警告?

编辑:感谢您的建议。丹尼尔的想法很好,但似乎并不适用于泛型类型,如下例所示

def test[T] = (Alice !? (100,"Hello")) match { 
   case Some(i: Int) => println ("Int received "+i) 
   case Some(t: T) => println ("T received ") 
   case _ =>  
}

遇到以下错误警告:警告:类型模式T中的抽象类型T未被选中,因为它被删除消除

解决方法

这是由于类型删除。除了数组之外,JVM不知道任何类型的参数。因此,Scala代码无法检查Option是Option [Int]还是Option [String] – 信息已被删除。

虽然如此,您可以修复代码:

object Test {
  def test = {
    (Alice !? (100,"Hello")) match {
      case Some(i: Int) => println ("Int received "+i)
      case Some(s: String) => println ("String received "+s)
      case _ =>
    }
    (Alice !? (100,1)) match {
      case Some(i: Int) => println ("Int received "+i)
      case Some(s: String) => println ("String received "+s)
      case _ =>
    }
  }
}

这样你不会测试Option的类型,但是它的内容类型是什么 – 假设有任何内容。 A无将落在默认情况下。

(编辑:李大同)

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

    推荐文章
      热点阅读