How to return null from a generic function in Scala?

后端 未结 3 1882
遥遥无期
遥遥无期 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:33

    As said in comments, this solution doesn't work

    If I understood your problem well, you can also assign default values, as explained in details in what does it mean assign "_" to a field in scala?. You can find more infos in 4.2 Variable Declarations and Definitions of the The Scala Language Specification

    So you can simply do:

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

    which will set unwrap with null without the type mismatch.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-16 15:42

    The "correct" solution is to do something which will immediately fail. Like so:

    def unwrap[T](iface: Class[T]): T = sys.error("unimplemented")
    

    In scala 2.10, this would have been implemented as:

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

    Because there is a new method in Predef called ???. This works because an expression of the form throw new Exception has the type Nothing, which is a subtype of any type (it is called bottom in type-theoretical circles).

    The reason that this is correct is that it is much better to fail instantly with an error, rather than use a null which may fail later and obfuscate the cause.

    0 讨论(0)
提交回复
热议问题