如何防止编译器选择最不通用的类型? [英] How to prevent compiler from choosing the least generic type?

查看:72
本文介绍了如何防止编译器选择最不通用的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法可以为特定类的实例查找一些存储空间:

I have a method that looks up some storage for an instance of a particular class:

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,那么那当然是行不通的:

It works well, but the problem is that if I don't provide an explicit type, the compiler chooses Null for T, and of course it doesn't work then:

def print(msg: String) = { /* ... */ }

print(lookup);

打印Null,当然什么也没找到.显然,编译器推断出可能的最小通用类型.

prints Null and of course nothing is found. Clearly the compiler infers the least generic type possible.

如果我添加像这样的显式类型

If I add an explicit type like

print(lookup[String]);

它工作正常.但这很容易出错.我想要:

it works fine. But this is very error-prone. I'd like to either:

  1. 让编译器始终选择最通用的类​​型,而不是最通用的类​​型.因此,在print(lookup)中,最通用的类​​型是String,因此我希望编译器为T推断String.或者
  2. 以某种方式强迫我总是写一个明确的类型,并在我编写print(lookup)之类的代码时发出编译时错误.
  1. Let the compiler to always choose the most generic possible type, instead of the least generic possible one. So in print(lookup) the most generic possible type is String, so I'd like the compiler to infer String for T. Or
  2. Force somehow that an explicit type is always present and issue a compile-time error when I write just something like print(lookup).

这有可能吗?

推荐答案

1)大多数通用类型是 AnyRef .

1) Most generic type is AnyRef.

2)您可以使用此答案中的=!=:

2) You could use =!= from 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

这篇关于如何防止编译器选择最不通用的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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