提供子类实例代替超类时的Scala错误?
我只是在Scala中尝试了一下,我写了此代码
object Main:
def main(args: Array[String]): Unit =
val dInt: Data[Int] = IntData(1)
val dString: Data[String] = StringData("hello")
val Data(deconstructedInt) = dInt // unapply
val Data(deconstructedString) = dString // unapply
println(deconstructedInt)
println(deconstructedString)
sealed trait Data[+T]:
def get: T
case class IntData(get: Int) extends Data[Int]
case class StringData(get: String) extends Data[String]
object Data:
def apply[T](input: T): Data[T] = input match {
case i: Int => IntData(i) //compile error here
case s: String => StringData(s) //compile error here
}
def unapply[T](d: Data[T]): Option[String] = d match {
case IntData(get) => Some(s"int data => get = $get")
case StringData(get) => Some(s"string data => get = $get")
}
,我在代码中评论的位置获得了此错误
Found: IntData
Required: Data[T]
case i: Int => IntData(i)
,为什么我会遇到此错误,不是intdata
(或string> Stringdata )
数据的子类
?
I am just trying things out in scala and I wrote this code
object Main:
def main(args: Array[String]): Unit =
val dInt: Data[Int] = IntData(1)
val dString: Data[String] = StringData("hello")
val Data(deconstructedInt) = dInt // unapply
val Data(deconstructedString) = dString // unapply
println(deconstructedInt)
println(deconstructedString)
sealed trait Data[+T]:
def get: T
case class IntData(get: Int) extends Data[Int]
case class StringData(get: String) extends Data[String]
object Data:
def apply[T](input: T): Data[T] = input match {
case i: Int => IntData(i) //compile error here
case s: String => StringData(s) //compile error here
}
def unapply[T](d: Data[T]): Option[String] = d match {
case IntData(get) => Some(s"int data => get = $get")
case StringData(get) => Some(s"string data => get = $get")
}
I get at the location commented in the code this error
Found: IntData
Required: Data[T]
case i: Int => IntData(i)
why I am getting this error, isn't IntData
(or StringData
) a subclass of Data
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
intdata
是data [int]
的子类型。因此,如果t
不是int
,intdata
是 不是data [t]
的子类型代码>。现在,您可能会说,如果
输入
与第一种情况匹配,则清楚地t
是int
。但是编译器并不明智地意识到这一点!您可以尝试使用Scala 3的新匹配类型:
另一种选择是联合类型:
但是,您将失去类型的信息。使用匹配类型解决方案,
应用(42)
被推断为具有类型intdata
。使用联合类型解决方案,可以推断具有类型数据[int |字符串]
。IntData
is a subtype ofData[Int]
. So ifT
is notInt
,IntData
is not a subtype ofData[T]
. Now, you might say, ifinput
matches the first case, then clearlyT
isInt
. But the compiler is not smart to realise this!You could try using Scala 3's new match types:
Another alternative is union types:
However, you will lose type information in doing this. Using the match types solution,
apply(42)
is inferred to have typeIntData
. Using the union types solution, it is inferred to have typeData[Int | String]
.通过这种方式,编译器将 T 之间的点连接起来并且可以工作:
This way compiler connects the dots between
T
s and it works: