Created
November 23, 2021 21:28
-
-
Save jaymody/b2925c1b2d26aafa501f7f555223b5e9 to your computer and use it in GitHub Desktop.
The many ways to write the signature of a function in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Main extends App { | |
// lambda function type are specified, type signature is inferred (works for both val and def) | |
val map1 = (f: (Int) => Int, l: Seq[Int]) => { for (x <- l) yield f(x) } | |
// lambda function types and result type are specified, type signature is inferred (works for both val and def) | |
val map2 = (f: (Int) => Int, l: Seq[Int]) => { for (x <- l) yield f(x) } : Seq[Int] | |
// type signature is specified, lambda function parameter types inferred (works for both val and def) | |
val map3: ((Int) => Int, Seq[Int]) => Seq[Int] = (f, l) => { for (x <- l) yield f(x) } | |
// // type signature and lambda function parameter types are specified (works for both val and def) | |
val map4: ((Int) => Int, Seq[Int]) => Seq[Int] = (f: (Int) => Int, l: Seq[Int]) => { for (x <- l) yield f(x) } | |
// type signature, result, and lambda function parameter types are specified (works for both val and def) | |
val map5: ((Int) => Int, Seq[Int]) => Seq[Int] = (f: (Int) => Int, l: Seq[Int]) => { for (x <- l) yield f(x) } : Seq[Int] | |
// method definition with type signature inline with function parameters, result type is inferred | |
def map6(f: (Int) => Int, l: Seq[Int]) = { for (x <- l) yield f(x) } | |
// method definition with type signature inline with function parameters, result type is specified | |
def map7(f: (Int) => Int, l: Seq[Int]): Seq[Int] = { for (x <- l) yield f(x) } | |
// "best" definition of map, using generics and inline type signature | |
def map8[A, B](f: (A) => B, l: Seq[A]): Seq[B] = { for (x <- l) yield f(x) } | |
// test map functions | |
val double: (Int) => Int = (x: Int) => x * 2 | |
val mySeq = 1 to 10 | |
println(map1(double, mySeq)) | |
println(map2(double, mySeq)) | |
println(map3(double, mySeq)) | |
println(map4(double, mySeq)) | |
println(map5(double, mySeq)) | |
println(map6(double, mySeq)) | |
println(map7(double, mySeq)) | |
println(map8(double, mySeq)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment