How to return null from a generic function in Scala?

后端 未结 3 1891
遥遥无期
遥遥无期 2020-12-16 15:04

I am writing my own simple javax.sql.DataSource implementation, the only method of it I need to work is getConnection: Connection, but the interfac

3条回答
  •  不知归路
    2020-12-16 15:41

    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
    

提交回复
热议问题