How do you declare a function in Scala that returns itself (or another function with the same signature)?

Nick Holt

First the background - I am writing some code to decode messages received from a socket. The nature of sockets means that these messages, received as ByteStrings may be complete, truncated or concatenated with other messages. The messages themselves are broken into a common header which contains the length of the variable data which follows.

My plan was to have functions that read the parts of the message, for example the first read could read the length of the variable data, the second the variable data itself.

When one of these methods is called, I want it to return the next operation which could be the next logical operation in the read sequence or itself if the particular read could not be performed because all the data required is yet to be received.

In the case that the data received from the socket is perfectly framed, the read operations would alternate between readLength and readData. However when data is read in multiple chunks from the socket it may be that the read operations follow a readLength, readData and readData pattern.

Hope that made sense.

What I want to do is something like this (which won't compile because of the cyclic reference):

type ReadFunction = (ByteBuffer) => ReadFunction

So that I can declare something like this:

def readLength(buffer: ByteBuffer): ReadFunction = {

  if (buffer.limit - buffer.position > 4) {

    return readData(buffer.getInt)
  }
  else {

    return readLength
  }
}

def readData(length: Int)(buffer: ByteBuffer): ReadFunction = {

  if (buffer.limit - buffer.position > length) {

    val data: Array[Byte](size)
    buffer.get(data) 

    //process data

    readLength   
  }
  else {

    readData(length)
  }
}

Now I know I can (and actually have) solve this by defining the read operations as classes that extend a common trait and return instances of each but that seems rather un-Scala like.

So my question is - how do you define a function that can return itself?

senia

You can't use cyclic reference in type declaration, but you can use it in class or trait declaration like this:

implicit class ReadFunction(f: Int => ReadFunction) extends (Int => ReadFunction) {
  def apply(i: Int) = f(i)
}

lazy val read: ReadFunction = { i: Int => println(i); read }

scala> read(1)(2)(3)
1
2
3
res0: ReadFunction = <function1>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to define function in Scala that returns a function that itself returns a function

How do I write a function that returns itself?

Returning a function with the same signature as itself in C#

How to declare function with anonymous enum in function signature?

How do you declare a function interface without exposing Function properties

How do I declare a function that returns a pointer to a function that returns a function pointer without using a typedef in C?

Declare a function signature with decltype()

How to type annotate "function wrappers" (function which returns a function with the same signature as it's argument)

How to declare a function pointer that returns a function pointer

How do I write a function that returns another function?

How do you add two Class Member Functions together with another function inside the same class?

How to declare a generic function that returns a function (react hook) with same parameters but different return type from its parameter

Do you have to declare a function's type?

React - How do you call a function from inside another function

How do you pass a named parameter into a function that another function needs?

How to declare std::function for any member function with specific signature?

How do I declare the signature of a function that must return one of its arguments? (in any language*)

How do you selectively simplify arguments to each time a function is called, without evaluating the function itself?

missing parameter type for expanded function for my function; not for another with same signature

How to declare generics for a method that returns a Function with generics

How to declare function that returns an array of object?

How to declare a protocol with a function that returns NavigationLink

how do you declare a lambda function using typedef and then use it by passing to a function?

scala function takes function which returns another function

How do you annotate a flowtype of a function that returns a slice of state?

How do you print a function that returns a request in Python?

How do you check if your function returns nothing?

How to declare a function with val in Scala that takes no Input

How to declare variable argument abstract function in Scala

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive