0

I'm looking at this sample code and after entering it in the scala repl I can see how it works.

val twice: Int => Int =
  x => x * 2

This is similar:

val parse: String => Option[Int] =
  s => if(s.matches("-?[0-9]+")) Some(s.toInt) else None 

Can someone please deconstruct the above method and explain how this works?

I can see the name twice or parse, followed by the type which is Int => Int or String => Option[Int].

Now in the 2nd line of both functions you have a variable x or s. I can only assume this is the parameter.

Also if you can expand on what scala features allow a function to be written like this.

Thanks!

Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • `val fn: A => B = a => doSomeBFrom(a)` (or `val fn: A => B = { a: A => doSomeBFrom(a) }`) is equivalent to `def fn(a: A): B = doSomeBFrom(a)` – cchantep Jul 06 '20 at 10:46
  • 4
    Does this answer your question? [Right Arrow meanings in Scala](https://stackoverflow.com/questions/3878347/right-arrow-meanings-in-scala) – cchantep Jul 06 '20 at 10:47
  • This is basic Scala syntax for creating lambdas, any course or book about the language should have covered this. If you aren't following any, I recommend you to do so. – Luis Miguel Mejía Suárez Jul 06 '20 at 13:26
  • @LuisMiguelMejíaSuárez I tried reading this https://docs.scala-lang.org/overviews/scala-book/anonymous-functions.html but it didn't cover it well sorry. – Blankman Jul 06 '20 at 15:50
  • @Blankman no problem, I just thought you were trying to learn scala without following any material, that would be painful. If you look carefully, you can see they cover the lambda syntax right there `(_ * 2) === x => x * 2` – Luis Miguel Mejía Suárez Jul 06 '20 at 17:40

1 Answers1

2

The expected type of value

x => x * 2

is

Int => Int

which de-sugars to

Function1[Int, Int]

hence function definition

val twice: Int => Int = x => x * 2

is equivalent to

val twice: Function1[Int, Int] = new Function1[Int, Int] {
  override def apply(x: Int) = x * 2
}

as per SLS 6.3 Anonymous Functions.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98