Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8444639
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T09:26:42+00:00 2026-06-10T09:26:42+00:00

For a numeric intensive code I have written a function with the following signature:

  • 0

For a numeric intensive code I have written a function with the following signature:

def update( f: (Int,Int,Double) => Double ): Unit = {...}

However, because Function3 is not specialized, every application of f results in boxing/unboxing the 3 arguments and the result type.

I could use a special updater class:

trait Updater {
  def apply( i: Int, j: Int, x: Double ): Double
}
def update( f: Updater ): Unit = {...}

But the invocation is cumbersome (and java-ish):

//with function
b.update( (i,j,_) => if( i==0 || j ==0 ) 1.0 else 0.5 )

//with updater
b.update( new Updater {
  def apply( i: Int, j: Int, x: Double ) = if( i==0 || j ==0 ) 1.0 else 0.5
} )

Is there a way to avoid boxing/unboxing while still using the lambda syntax ? I was hoping macros will help, but I cannot figure any solution.

EDIT: I analyzed the function3 generated byte code with javap. An unboxed method is generated by the compiler, along the generic method (see below). Is there a way to call the unboxed one directly ?

public final double apply(int, int, double);
  Code:
   0:   ldc2_w  #14; //double 100.0d
   3:   iload_2
   4:   i2d
   5:   dmul
   6:   iload_1
   7:   i2d
   8:   ddiv
   9:   dreturn

public final java.lang.Object apply(java.lang.Object, java.lang.Object, java.lang.Object);
  Code:
   0:   aload_0
   1:   aload_1
   2:   invokestatic    #31; //Method scala/runtime/BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I
   5:   aload_2
   6:   invokestatic    #31; //Method scala/runtime/BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I
   9:   aload_3
   10:  invokestatic    #35; //Method scala/runtime/BoxesRunTime.unboxToDouble:(Ljava/lang/Object;)D
   13:  invokevirtual   #37; //Method apply:(IID)D
   16:  invokestatic    #41; //Method scala/runtime/BoxesRunTime.boxToDouble:(D)Ljava/lang/Double;
   19:  areturn
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T09:26:43+00:00Added an answer on June 10, 2026 at 9:26 am

    Since you mentioned macros as a possible solution, I got the idea of writing a macro that takes an anonymous function, extracts the apply methods and inserts it into an anonymous class that extends a custom function trait called F3. This is the quite long implementation.

    The trait F3

    trait F3[@specialized A, @specialized B, @specialized C, @specialized D] {
      def apply(a:A, b:B, c:C):D
    }
    

    The macro

      implicit def function3toF3[A,B,C,D](f:Function3[A,B,C,D]):F3[A,B,C,D] = macro impl[A,B,C,D]
    
      def impl[A,B,C,D](c:Context)(f:c.Expr[Function3[A,B,C,D]]):c.Expr[F3[A,B,C,D]] = {
        import c.universe._
        var Function(args,body) = f.tree
        args = args.map(c.resetAllAttrs(_).asInstanceOf[ValDef])
        body = c.resetAllAttrs(body)
        val res = 
          Block(
            List(
              ClassDef(
                Modifiers(Flag.FINAL),
                newTypeName("$anon"),
                List(),
                Template(
                  List(
                    AppliedTypeTree(Ident(c.mirror.staticClass("mcro.F3")),
                      List(
                        Ident(c.mirror.staticClass("scala.Int")),
                        Ident(c.mirror.staticClass("scala.Int")),
                        Ident(c.mirror.staticClass("scala.Double")),
                        Ident(c.mirror.staticClass("scala.Double"))
                      )
                    )
                  ),
                  emptyValDef,
                  List(
                    DefDef(
                      Modifiers(),
                      nme.CONSTRUCTOR,
                      List(),
                      List(
                        List()
                      ),
                      TypeTree(),
                      Block(
                        List(
                          Apply(
                            Select(Super(This(newTypeName("")), newTypeName("")), newTermName("<init>")),
                            List()
                          )
                        ),
                        Literal(Constant(()))
                      )
                    ),
                    DefDef(
                      Modifiers(Flag.OVERRIDE),
                      newTermName("apply"),
                      List(),
                      List(args),
                      TypeTree(),
                      body
                    )
                  )
                )
              )
            ),
            Apply(
              Select(
                New(
                  Ident(newTypeName("$anon"))
                ),
                nme.CONSTRUCTOR
              ),
              List()
            )
          )
    
    
    
    
        c.Expr[F3[A,B,C,D]](res)
      }
    

    Since I defined the macro as implicit, it can be used like this:

    def foo(f:F3[Int,Int,Double,Double]) = {
      println(f.apply(1,2,3))
    }
    
    foo((a:Int,b:Int,c:Double)=>a+b+c)
    

    Before foo is called, the macro is invoked because foo expects an instance of F3. As expected, the call to foo prints “6.0”. Now let’s look at the disassembly of the foo method, to make sure that no boxing/unboxing takes place:

    public void foo(mcro.F3);
      Code:
       Stack=6, Locals=2, Args_size=2
       0:   getstatic       #19; //Field scala/Predef$.MODULE$:Lscala/Predef$;
       3:   aload_1
       4:   iconst_1
       5:   iconst_2
       6:   ldc2_w  #20; //double 3.0d
       9:   invokeinterface #27,  5; //InterfaceMethod mcro/F3.apply$mcIIDD$sp:(IID)D
       14:  invokestatic    #33; //Method scala/runtime/BoxesRunTime.boxToDouble:(D)Ljava/lang/Double;
       17:  invokevirtual   #37; //Method scala/Predef$.println:(Ljava/lang/Object;)V
       20:  return
    

    The only boxing that is done here is for the call to println. Yay!

    One last remark: In its current state, the macro only works for the special case of Int,Int,Double,Double but that can easily be fixed. I leave that as an exercise to the reader.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

PRINT CONVERT(NUMERIC(18,0), '') produces Error converting data type varchar to numeric. However, PRINT CONVERT(INT,
I have two numeric fields that contain the following information: (1) Users Registered (2)
I have a numeric vector (future_prices) in my case. I use a date vector
I have a numeric vector, it contains patches of elements that are repeating, something
I have 4 numeric up down controls on a form. They are set to
How to have numeric keyboard popup to input in TextBox on Windows Mobile 6.53?
I have following type of data and I want to produce bar graph. Mark
How to do numeric validation using JQuery. I have to validate my price field
I have a UIPicker with 3 components containing numeric values, this allows the user
I try to read numeric/decimal/money columns from SQL Server via ODBC in the following

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.