在Scala中初始化通用变量 [英] Initializing Generic Variables in Scala
本文介绍了在Scala中初始化通用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不初始化(或初始化为任何值)的情况下在Scala中声明泛型变量?
How do I declare a generic variable in Scala without initializing it (or initializing to any value)?
def foo[T] {
var t: T = ???? // tried _, null
t
}
推荐答案
def foo[T] {
var t: T = null.asInstanceOf[T]
t
}
而且,如果您不喜欢其中涉及的仪式,则可以通过以下方式简化它:
And, if you don't like the ceremony involved in that, you can ease it this way:
// Import this into your scope
case class Init()
implicit def initToT[T](i: Init): T = {
null.asInstanceOf[T]
}
// Then use it
def foo[T] {
var t: T = Init()
t
}
这篇关于在Scala中初始化通用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文