函数类型可以通过推理来定义吗?
Can function type be defined by inference?
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,"")
}
Scala 中是否有类似 C++ decltype 的东西可以用于此目的?
我不太确定你想在这里实现什么,如果我理解正确的话你想避免输入两次 (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
,因为类型不是第一个 class 公民,例如在 Idris 中。也就是说,您应该能够使用 Shapeless and/or 宏来编写它。
如果您想固定类型和参数并重新使用它们,最简单的解决方案是将它们变成 case class
。然后您可以使用 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,""))
}
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,"")
}
Scala 中是否有类似 C++ decltype 的东西可以用于此目的?
我不太确定你想在这里实现什么,如果我理解正确的话你想避免输入两次 (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
,因为类型不是第一个 class 公民,例如在 Idris 中。也就是说,您应该能够使用 Shapeless and/or 宏来编写它。
如果您想固定类型和参数并重新使用它们,最简单的解决方案是将它们变成 case class
。然后您可以使用 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,""))
}