-
Notifications
You must be signed in to change notification settings - Fork 330
/
Copy pathByNameParameter.scala
70 lines (57 loc) · 1.95 KB
/
ByNameParameter.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* scala-exercises - exercises-stdlib
* Copyright (C) 2015-2016 47 Degrees, LLC. <http://www.47deg.com>
*/
package stdlib
import org.scalatest._
/** @param name byname_parameter
*/
object ByNameParameter extends FlatSpec with Matchers with org.scalaexercises.definitions.Section {
/** `() => Int` is a Function type that takes a `Unit` type. `Unit` is known as `void` to a Java programmer. The function returns an `Int`. You can place this as a method parameter so that you can use it as a block, but still it doesn't look quite right:
*/
def takesUnitByNameParameter(res0: Either[Throwable, Int]) {
def calc(x: () ⇒ Int): Either[Throwable, Int] = {
try {
Right(x()) //An explicit call of the x function
} catch {
case b: Throwable ⇒ Left(b)
}
}
val y = calc { () ⇒ //Having explicitly declaring that Unit is a parameter with ()
14 + 15
}
y should be(res0)
}
/** A by-name parameter does the same thing as the previous koan but there is no need to explicitly handle `Unit` or `()`. This is used extensively in Scala to create blocks:
*/
def byNameParameter(res0: Either[Throwable, Int]) {
def calc(x: ⇒ Int): Either[Throwable, Int] = {
//x is a call by name parameter
try {
Right(x)
} catch {
case b: Throwable ⇒ Left(b)
}
}
val y = calc {
//This looks like a natural block
println("Here we go!") //Some superfluous call
val z = List(1, 2, 3, 4) //Another superfluous call
49 + 20
}
y should be(res0)
}
/** By name parameters can also be used with `object` and `apply` to make interesting block-like calls:
*/
def withApplyByNameParameter(res0: String) {
object PigLatinizer {
def apply(x: ⇒ String) = x.tail + x.head + "ay"
}
val result = PigLatinizer {
val x = "pret"
val z = "zel"
x ++ z //concatenate the strings
}
result should be(res0)
}
}