0

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.)

1

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know about SAM, it sounds like something I was looking for. Thanks!
0

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.