如何从Scala中的泛型函数返回null? [英] How to return null from a generic function in Scala?

查看:800
本文介绍了如何从Scala中的泛型函数返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写自己的简单的 javax.sql.DataSource 实现,我需要的唯一方法是 getConnection:Connection code>,但接口从 javax.sql.CommonDataSource java.sql中继承了许多其他方法(我不需要) .Wrapper 。所以,我想实施那些不需要的方法,这样他们就不会真正起作用,但在被调用时会表现出合适的方式。例如,我将 boolean isWrapperFor(Class <?> iface)作为

  def isWrapperFor(iface:Class [_]):Boolean = false 

我想实现< T> T解包(Class< T> iface)

  def unwrap [T](iface:Class [T]):T = null 

但最后不起作用:编译器报告类型不匹配。

使用 null.asInstanceOf [T] 还是有更好的方法吗?当然,我认为只是抛出 UnsupportedOperationException ,而不是在这个特定的情况下,但恕我直言,这个问题仍然可以是有趣的。

解决方案

这是因为 T 可能是一个不可为空的类型。当你强制执行 T 为可空类型时:

  def unwrap [T>:Null](iface:Class [T]):T = null 

unwrap(classOf [String])//编译

unwrap(classOf [ Int])//不能编译,因为Int不能为空


I am writing my own simple javax.sql.DataSource implementation, the only method of it I need to work is getConnection: Connection, but the interface inherits many other methods (which I don't need) from javax.sql.CommonDataSource and java.sql.Wrapper. So, I would like to "implement" those unneeded methods a way they wouldn't actually work but would behave an adequate way when called. For example I implement boolean isWrapperFor(Class<?> iface) as

def isWrapperFor(iface: Class[_]): Boolean = false

and I'd like to implement <T> T unwrap(Class<T> iface) as

def unwrap[T](iface: Class[T]): T = null

But the last doesn't work: the compiler reports type mismatch.

Will it be correct to use null.asInstanceOf[T] or is there a better way? Of course I consider just throwing UnsupportedOperationException instead in this particular case, but IMHO the question can still be interesting.

解决方案

This is because T could be a non-nullable type. It works when you enforce T to be a nullable type:

def unwrap[T >: Null](iface: Class[T]): T = null

unwrap(classOf[String]) // compiles

unwrap(classOf[Int]) // does not compile, because Int is not nullable

这篇关于如何从Scala中的泛型函数返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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