Scala 类型推断非常好,而且很容易习惯,不必编写两次。当你不得不这么做的时候,你会更痛苦。函数类型就是这样的一个例子。
有时我想为某些函数签名创建一个命名类型。有可能吗?有没有办法获取函数的编译时类型,这样我在定义 FType 时就不必再次输入它?
object Foo {
def f(a:Int, b:Int, x:Double, y:Double, name:String) : Unit = {}
//type FType = typeOf(f) // can compiler provide me a compile time type somehow?
type FType = (Int,Int,Double,Double,String) => Unit
def callF( func:FType) = func(0,0,0,0,"")
}
有没有类似 C++ decltype 的东西Scala 中哪个可以用于此目的?
最佳答案
我不太确定你想在这里实现什么,如果我理解正确的话,你想避免输入 (a:Int, b:Int, x:Double, y:Double, name:String )
两次。
您可以自己预先定义FType
,然后简单地在f
和callF
中重用它吗?
object Foo {
type FType = (Int,Int,Double,Double,String) => Unit
def f: FType = (a, b, x, y, name) => ()
def callF(func: FType) = func(0,0,0,0,"")
}
如果您确实想抽象 FType
,这是一个明显不同的问题,但情况似乎并非如此,因为您通过调用 func(0 ,0,0,0,"")
。
Scala 中没有 decltype
因为类型不像 Idris 中那样不是一等公民。也就是说,您应该能够使用 Shapeless 来编写它和/或宏。
如果您想修复类型和参数并重用它们,最简单的解决方案是将它们转换为 case 类
。然后,您可以使用 import
直接访问您的字段:
object Foo {
case class FArgs(a: Int, b: Int, x: Double, y: Double, name: String)
def f(args: FArgs): Unit = {
import args._
println(name) // or whatever you want to do
}
def callF(func: FArgs => Unit) = func(FArgs(0,0,0,0,""))
}
关于function - 函数类型可以通过推理来定义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29034921/