gpt4 book ai didi

Scala 模式匹配与 Option[Any] 混淆

转载 作者:行者123 更新时间:2023-12-03 08:37:38 27 4
gpt4 key购买 nike

我有以下 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)

解释是什么?

作为第二个问题,我得到 unchecked上述警告如下:
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

我怎样才能避免这些警告?

编辑:感谢您的建议。 Daniel 的想法不错,但似乎不适用于泛型类型,如下例所示
def test[T] = (Alice !? (100, "Hello")) match { 
case Some(i: Int) => println ("Int received "+i)
case Some(t: T) => println ("T received ")
case _ =>
}

遇到以下错误警告: warning: abstract type T in type pattern T is unchecked since it is eliminated by erasure

最佳答案

这是由于类型删除。 JVM 不知道任何类型参数,除了数组。因此,Scala 代码无法检查 OptionOption[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 的类型。是,但其内容的类型是什么——假设有任何内容。一个 None将落入默认情况。

关于Scala 模式匹配与 Option[Any] 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3788358/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com