the21st
the21st

Reputation: 1096

Scala: Naming parameters of function parameters

I have an Image trait that represents a 2D ARGB image. Image has a map method which takes a mapping function and transforms the image using said function. The mapping function has 3 parameters: the X and Y coordinates and the color of the image at that coordinate. The color is represented as a 32-bit ARGB value packed into an Int.

trait Image {
    def map(f: (Int, Int, Int) => Int)
}

However, without a comment, it's impossible to tell which parameter of f is which.

In C#, I would create a delegate for this, which allows me to name the parameters of the mapping function:

delegate int MapImage(int x, int y, int color);

Is there anything of this sort in Scala? Is it being considered for addition to the language? Without it, I cannot write an interface that is readable without explicit documentation.

(Note: I know I should wrap the Int in a case class for the purposes of representing a color, but this is just an illustrative example.)

Upvotes: 0

Views: 120

Answers (2)

lmm
lmm

Reputation: 17431

You could declare a trait that f implements. With SAM support (enabled if you compile with -Xexperimental, and will be in the next version) this should be just as easy to use.

trait ImageMapper {
  def mapImage(x: Int, y: Int, color: Int): Int
}

trait Image {
  def map(f: ImageMapper) = ...
}

myImage.map{ (x, y, color) => ... } //the anonymous function
// is automatically "lifted" to be an implementation of the trait.

Upvotes: 1

bjfletcher
bjfletcher

Reputation: 11518

Perhaps through using types:

trait Image {
  type x = Int
  type y = Int
  type color = Int

  def map(f: (x, y, color) => Int)
}

I'd much rather using case class like so:

case class MapImage(x: Int, y: Int, color: Int)
trait Image {
  def map(f: MapImage => Int)
}

Upvotes: 0

Related Questions