我有一个方法可以查找特定类的实例的一些存储:
def lookup[T >: Null: ClassTag]: T = {
// Print what class tag we got:
System.out.println(implicitly[ClassTag[T]].toString);
null; // details omitted, just return null
}
它工作得很好,但问题是,如果我不提供显式类型,编译器会为 T
选择 Null
,当然它不会然后工作:
def print(msg: String) = { /* ... */ }
print(lookup);
打印Null
,当然什么也没找到。显然,编译器推断出可能的最不泛型类型。
如果我添加一个显式类型,例如
print(lookup[String]);
效果很好。但这非常容易出错。我想要:
- 让编译器始终选择最通用的可能类型,而不是最不通用的可能类型。因此,在
print(lookup)
中,最通用的可能类型是String
,因此我希望编译器推断String
为T
。或者 - 以某种方式强制显式类型始终存在,并在我编写类似
print(lookup)
之类的内容时发出编译时错误。
这可能吗?
最佳答案
1) 最通用的类型是 AnyRef
.
2) 您可以使用 this answer 中的 =!=
:
scala> def lookup[T >: Null: ClassTag](implicit guard: T =!= Null ): T = {
| null; // details omitted, just return null
| }
lookup: [T >: Null](implicit evidence$1: scala.reflect.ClassTag[T], implicit guard: =!=[T,Null])T
scala> lookup
<console>:11: error: ambiguous implicit values:
both method equal in trait LowerPriorityImplicits of type [A]=> =!=[A,A]
and method nequal in object =!= of type [A, B](implicit same: =:=[A,B])=!=[A,B]
match expected type =!=[Null,Null]
lookup
^
scala> lookup[String]
res3: String = null
关于scala - 如何防止编译器选择最少泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16425502/