Can a function type be determined by output?

Scala's type inference is really good, and it's not easy to get used to writing things twice. The hurt when you need to. One such example is function types.

Sometimes I would like to create a named type for some function signature. Is it possible somehow? Is there a way to get the compile time type so I don't have to type it again when defining 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,"") } 

Is there something like C ++ decltype in Scala that can be used for this purpose?

+2
source share
1 answer

I'm not quite sure what you are trying to achieve here, if I understand correctly, you want not to print (a:Int, b:Int, x:Double, y:Double, name:String) twice.

How about defining FType yourself and then just reusing it in f and 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,"") } 

If you really want to FType , this is a much different problem, but it doesn't seem to be that way, since you force the type by calling func(0,0,0,0,"") .

You do not have decltype in Scala, because types are not first class citizens, for example, they can be in Idris, for example. However, you must write this using Shapeless and / or macros.

If you want to fix the types and arguments and reuse them, the easiest solution is to turn them into a case class . Then you can use import to directly access your fields:

 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,"")) } 
+2
source

Source: https://habr.com/ru/post/1215311/


All Articles