复合类型的案例类伴随对象生成错误 [英] Case class companion object generation error for compound type

查看:83
本文介绍了复合类型的案例类伴随对象生成错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义的空特性测试:

trait Test

用于复合类型的内容:

scala> val a : Int with Test = 10.asInstanceOf[Int with Test]
a: Int with Test = 10

和带有复合类型参数的案例类(例如未装箱的标记类型):

and case class with parameter of compound type (like Unboxed Tagged Type):

scala> case class Foo(a: Int with Test)
error: type mismatch;
 found   : Double
 required: AnyRef
Note: an implicit exists from scala.Double => java.lang.Double, but
methods inherited from Object are rendered ambiguous.  This is to avoid
a blanket implicit which would convert any scala.Double to any AnyRef.
You may wish to use a type ascription: `x: java.lang.Double`.

但是它非常适合:

scala> case class Foo(a: List[Int] with Test)
defined class Foo

方法定义也没问题:

scala> def foo(a: Int with Test) = ???
foo: (a: Int with Test)Nothing

Scala版本 2.10.3

Scala version 2.10.3

这是正常的编译器行为吗?

Is it normal compiler behaviour?

推荐答案

您遇到了Scala统一原语和对象的尝试失败的情况之一.由于Scala中的Int表示Java基本类型int,因此不能将任何特征混入其中.当执行asInstanceOf时,Scala编译器会将Int自动装箱到java.lang.Integer中:

You've bumped into one of the cases where Scala's attempt to unify primitives and Objects breaks down. Since Int in Scala represents the Java primitive type int, it can't have any traits mixed into it. When doing asInstanceOf, the Scala compiler autoboxes the Int into a java.lang.Integer:

scala> val a: Int with Test = 10.asInstanceOf[Int with Test] 
a: Int with Test = 10

scala> a.getClass
res1: Class[_ <: Int] = class java.lang.Integer

但是,声明类型时不会自动装箱,因此您必须手动进行:

However, autoboxing doesn't happen when declaring types, so you have to do it by hand:

scala> case class Foo(x: Integer with Test)
defined class Foo

但是随后,编译器类型检查器将不会在检查类型之前自动装箱:

But then the compiler type checker won't autobox before checking the types:

scala> Foo(a)
<console>:12: error: type mismatch;
 found   : Int with Test
 required: Integer with Test
              Foo(a)
                  ^

因此您必须将变量声明为Integer with Test:

So you would have to declare your variable as Integer with Test:

scala> val a: Integer with Test = 10.asInstanceOf[Integer with Test]
a: Integer with Test = 10

scala> Foo(a)
res3: Foo = Foo(10)

或在调用案例类时使用强制转换:

or use a cast when calling the case class:

val a : Int with Test = 10.asInstanceOf[Int with Test]
scala> a: Int with Test = 10

scala> Foo(a.asInstanceOf[Integer with Test])
res0: Foo = Foo(10)

这篇关于复合类型的案例类伴随对象生成错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆