Skip to content

SCALA-32 #95

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
package com.baeldung.scala
package com.baeldung.scala.functionsandmethods

import scala.annotation.tailrec

object FunctionsAndMethods {
// Anonymous function execution
Expand All @@ -23,6 +25,27 @@ object FunctionsAndMethods {

// Here we defined a Value Class with extension method
implicit class IntExtension(val value: Int) extends AnyVal { def isOdd: Boolean = value % 2 == 0 }


def plot(f: Double => Double): List[Double] = {
val xs: Range = -10 to 10
xs.map(x => f(x)).toList
}

val lines: (Double, Double, Double) => Double = (a,b,x) => a * x + b

val line: (Double, Double) => Double => Double = (a,b) => x => lines(a,b,x)

def factorial(num: Int): Int = {
@tailrec
def fact(num: Int, acc: Int): Int = {
if (num == 0) acc else fact(num - 1, acc * num)
}

fact(num, 1)
}

def pop[T](seq: Seq[T]): T = seq.head
}


Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.baeldung.scala
package com.baeldung.scala.functionsandmethods

import org.junit.Assert.assertEquals
import org.junit.{Before, Test}
Expand Down Expand Up @@ -43,4 +43,33 @@ class FunctionsAndMethodsUnitTest {
assertEquals(true, 10.isOdd)
assertEquals(false, 11.isOdd)
}

@Test
def givenLine45_whenUseItInAPlot_thenCorrectResults(): Unit = {
val a45DegreeLine = FunctionsAndMethods.line(1,0)
val results = FunctionsAndMethods.plot(a45DegreeLine)
val expected = List(-10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0,
0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
assertEquals(expected, results)
}

@Test
def givenNestedMethod_whenUseIt_thenCorrectResults(): Unit = {
val factorialResult = FunctionsAndMethods.factorial(10)
val expected = 3628800;
assertEquals(expected, factorialResult)
}

@Test
def givenParameterizedMethod_whenUseIt_thenCorrectResults(): Unit = {
val strings = Seq("a", "b", "c")
val first = FunctionsAndMethods.pop(strings)
assertEquals("a", first)

val ints = Seq(10, 3, 11, 22, 10)
val second = FunctionsAndMethods.pop(ints)
assertEquals(10, second)


}
}