JAVA-911 Need to move existing scala code from java to scala repository
This commit is contained in:
parent
e7946b6558
commit
2833ef5bcd
|
@ -73,8 +73,6 @@ ninja/devDb.mv.db
|
|||
**/out-tsc
|
||||
**/nbproject/
|
||||
**/nb-configuration.xml
|
||||
core-scala/.cache-main
|
||||
core-scala/.cache-tests
|
||||
|
||||
|
||||
persistence-modules/hibernate5/transaction.log
|
||||
|
|
|
@ -1,8 +0,0 @@
|
|||
## Core Scala
|
||||
|
||||
This module contains articles about Scala's core features
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Scala](https://www.baeldung.com/scala-intro)
|
||||
- [Regular Expressions in Scala](https://www.baeldung.com/scala/regular-expressions)
|
|
@ -1,55 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-scala</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-scala</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.scala-lang</groupId>
|
||||
<artifactId>scala-library</artifactId>
|
||||
<version>${scala.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<sourceDirectory>src/main/scala</sourceDirectory>
|
||||
<testSourceDirectory>src/test/scala</testSourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>net.alchim31.maven</groupId>
|
||||
<artifactId>scala-maven-plugin</artifactId>
|
||||
<version>${scala.plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
<goal>testCompile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<args>
|
||||
<arg>-dependencyfile</arg>
|
||||
<arg>${project.build.directory}/.scala_dependencies</arg>
|
||||
</args>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<scala.version>2.12.7</scala.version>
|
||||
<scala.plugin.version>3.3.2</scala.plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
/**
|
||||
* Sample code demonstrating the various control structured.
|
||||
*
|
||||
* @author Chandra Prakash
|
||||
*
|
||||
*/
|
||||
object ControlStructuresDemo {
|
||||
def gcd(x : Int, y : Int) : Int = {
|
||||
if (y == 0) x else gcd(y, x % y)
|
||||
}
|
||||
|
||||
def gcdIter(x : Int, y : Int) : Int = {
|
||||
var a = x
|
||||
var b = y
|
||||
while (b > 0) {
|
||||
a = a % b
|
||||
val t = a
|
||||
a = b
|
||||
b = t
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
def rangeSum(a : Int, b : Int) = {
|
||||
var sum = 0;
|
||||
for (i <- a to b) {
|
||||
sum += i
|
||||
}
|
||||
sum
|
||||
}
|
||||
|
||||
def factorial(a : Int) : Int = {
|
||||
var result = 1;
|
||||
var i = 1;
|
||||
do {
|
||||
result *= i
|
||||
i = i + 1
|
||||
} while (i <= a)
|
||||
result
|
||||
}
|
||||
|
||||
}
|
|
@ -1,27 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
/**
|
||||
* Sample Code demonstrating a class.
|
||||
*
|
||||
* @author Chandra Prakash
|
||||
*
|
||||
*/
|
||||
class Employee(val name : String,
|
||||
var salary : Int,
|
||||
annualIncrement : Int = 20) {
|
||||
|
||||
def incrementSalary() : Unit = {
|
||||
salary += annualIncrement
|
||||
}
|
||||
|
||||
override def toString =
|
||||
s"Employee(name=$name, salary=$salary)"
|
||||
}
|
||||
|
||||
/**
|
||||
* A Trait which will make the toString return upper case value.
|
||||
*/
|
||||
trait UpperCasePrinter {
|
||||
override def toString: String = super.toString toUpperCase
|
||||
}
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
object HelloWorld extends App {
|
||||
println("Hello World!")
|
||||
args foreach println
|
||||
}
|
|
@ -1,27 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
/**
|
||||
* Sample higher order functions.
|
||||
*
|
||||
* @author Chandra Prakash
|
||||
*
|
||||
*/
|
||||
object HigherOrderFunctions {
|
||||
|
||||
def mapReduce(r : (Int, Int) => Int,
|
||||
i : Int,
|
||||
m : Int => Int,
|
||||
a : Int, b : Int): Int = {
|
||||
def iter(a : Int, result : Int) : Int = {
|
||||
if (a > b) result
|
||||
else iter(a + 1, r(m(a), result))
|
||||
}
|
||||
iter(a, i)
|
||||
}
|
||||
|
||||
def whileLoop(condition : => Boolean)(body : => Unit) : Unit =
|
||||
if (condition) {
|
||||
body
|
||||
whileLoop(condition)(body)
|
||||
}
|
||||
}
|
|
@ -1,34 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
/**
|
||||
* An abstract class for set of integers and its implementation.
|
||||
*
|
||||
* @author Chandra Prakash
|
||||
*
|
||||
*/
|
||||
abstract class IntSet {
|
||||
// add an element to the set
|
||||
def incl(x : Int) : IntSet
|
||||
|
||||
// whether an element belongs to the set
|
||||
def contains(x : Int) : Boolean
|
||||
}
|
||||
|
||||
class EmptyIntSet extends IntSet {
|
||||
|
||||
def contains(x : Int) : Boolean = false
|
||||
|
||||
def incl(x : Int) =
|
||||
new NonEmptyIntSet(x, this)
|
||||
}
|
||||
|
||||
class NonEmptyIntSet(val head : Int, val tail : IntSet)
|
||||
extends IntSet {
|
||||
|
||||
def contains(x : Int) : Boolean =
|
||||
head == x || (tail contains x)
|
||||
|
||||
def incl(x : Int) : IntSet =
|
||||
if (this contains x) this
|
||||
else new NonEmptyIntSet(x, this)
|
||||
}
|
|
@ -1,137 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
// Case Class
|
||||
abstract class Animal
|
||||
|
||||
case class Mammal(name: String, fromSea: Boolean) extends Animal
|
||||
|
||||
case class Bird(name: String) extends Animal
|
||||
|
||||
case class Fish(name: String) extends Animal
|
||||
|
||||
// Sealed Class
|
||||
sealed abstract class CardSuit
|
||||
|
||||
case class Spike() extends CardSuit
|
||||
|
||||
case class Diamond() extends CardSuit
|
||||
|
||||
case class Heart() extends CardSuit
|
||||
|
||||
case class Club() extends CardSuit
|
||||
|
||||
object Person {
|
||||
def apply(fullName: String) = fullName
|
||||
|
||||
def unapply(fullName: String): Option[String] = {
|
||||
if (!fullName.isEmpty)
|
||||
Some(fullName.replaceAll("(?<=\\w)(\\w+)", "."))
|
||||
else
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
class PatternMatching {
|
||||
|
||||
def caseClassesPatternMatching(animal: Animal): String = {
|
||||
animal match {
|
||||
case Mammal(name, fromSea) => s"I'm a $name, a kind of mammal. Am I from the sea? $fromSea"
|
||||
case Bird(name) => s"I'm a $name, a kind of bird"
|
||||
case _ => "I'm an unknown animal"
|
||||
}
|
||||
}
|
||||
|
||||
def constantsPatternMatching(constant: Any): String = {
|
||||
constant match {
|
||||
case 0 => "I'm equal to zero"
|
||||
case 4.5d => "I'm a double"
|
||||
case false => "I'm the contrary of true"
|
||||
case _ => s"I'm unknown and equal to $constant"
|
||||
}
|
||||
}
|
||||
|
||||
def sequencesPatternMatching(sequence: Any): String = {
|
||||
sequence match {
|
||||
case List(singleElement) => s"I'm a list with one element: $singleElement"
|
||||
case List(_, _*) => s"I'm a list with one or multiple elements: $sequence"
|
||||
case Vector(1, 2, _*) => s"I'm a vector: $sequence"
|
||||
case _ => s"I'm an unrecognized sequence. My value: $sequence"
|
||||
}
|
||||
}
|
||||
|
||||
def tuplesPatternMatching(tuple: Any): String = {
|
||||
tuple match {
|
||||
case (first, second) => s"I'm a tuple with two elements: $first & $second"
|
||||
case (first, second, third) => s"I'm a tuple with three elements: $first & $second & $third"
|
||||
case _ => s"Unrecognized pattern. My value: $tuple"
|
||||
}
|
||||
}
|
||||
|
||||
def typedPatternMatching(any: Any): String = {
|
||||
any match {
|
||||
case string: String => s"I'm a string. My value: $string"
|
||||
case integer: Int => s"I'm an integer. My value: $integer"
|
||||
case _ => s"I'm from an unknown type. My value: $any"
|
||||
}
|
||||
}
|
||||
|
||||
def regexPatterns(toMatch: String): String = {
|
||||
val numeric = """([0-9]+)""".r
|
||||
val alphabetic = """([a-zA-Z]+)""".r
|
||||
val alphanumeric = """([a-zA-Z0-9]+)""".r
|
||||
|
||||
toMatch match {
|
||||
case numeric(value) => s"I'm a numeric with value $value"
|
||||
case alphabetic(value) => s"I'm an alphabetic with value $value"
|
||||
case alphanumeric(value) => s"I'm an alphanumeric with value $value"
|
||||
case _ => s"I contain other characters than alphanumerics. My value $toMatch"
|
||||
}
|
||||
}
|
||||
|
||||
def optionsPatternMatching(option: Option[String]): String = {
|
||||
option match {
|
||||
case Some(value) => s"I'm not an empty option. Value $value"
|
||||
case None => "I'm an empty option"
|
||||
}
|
||||
}
|
||||
|
||||
def patternGuards(toMatch: Any, maxLength: Int): String = {
|
||||
toMatch match {
|
||||
case list: List[Any] if (list.size <= maxLength) => "List is of acceptable size"
|
||||
case list: List[Any] => "List has not an acceptable size"
|
||||
case string: String if (string.length <= maxLength) => "String is of acceptable size"
|
||||
case string: String => "String has not an acceptable size"
|
||||
case _ => "Input is neither a List or a String"
|
||||
}
|
||||
}
|
||||
|
||||
def sealedClass(cardSuit: CardSuit): String = {
|
||||
cardSuit match {
|
||||
case Spike() => "Card is spike"
|
||||
case Club() => "Card is club"
|
||||
case Heart() => "Card is heart"
|
||||
case Diamond() => "Card is diamond"
|
||||
}
|
||||
}
|
||||
|
||||
def extractors(person: Any): String = {
|
||||
person match {
|
||||
case Person(initials) => s"My initials are $initials"
|
||||
case _ => "Could not extract initials"
|
||||
}
|
||||
}
|
||||
|
||||
def closuresPatternMatching(list: List[Any]): List[Any] = {
|
||||
list.collect { case i: Int if (i < 10) => i }
|
||||
}
|
||||
|
||||
def catchBlocksPatternMatching(exception: Exception): String = {
|
||||
try {
|
||||
throw exception
|
||||
} catch {
|
||||
case ex: IllegalArgumentException => "It's an IllegalArgumentException"
|
||||
case ex: RuntimeException => "It's a RuntimeException"
|
||||
case _ => "It's an unknown kind of exception"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,33 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
/**
|
||||
* Some utility methods.
|
||||
*
|
||||
* @author Chandra Prakash
|
||||
*
|
||||
*/
|
||||
object Utils {
|
||||
def average(x : Double, y : Double): Double = (x + y) / 2
|
||||
|
||||
def randomLessThan(d : Double): Double = {
|
||||
var random = 0d
|
||||
do {
|
||||
random = Math.random()
|
||||
} while (random >= d)
|
||||
random
|
||||
}
|
||||
|
||||
def power(x : Int, y : Int) : Int = {
|
||||
def powNested(i : Int, accumulator : Int) : Int = {
|
||||
if (i <= 0) accumulator
|
||||
else powNested(i - 1, x * accumulator)
|
||||
}
|
||||
powNested(y, 1)
|
||||
}
|
||||
|
||||
def fibonacci(n : Int) : Int = n match {
|
||||
case 0 | 1 => 1
|
||||
case x if x > 1 =>
|
||||
fibonacci(x - 1) + fibonacci(x - 2)
|
||||
}
|
||||
}
|
|
@ -1,33 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
import com.baeldung.scala.ControlStructuresDemo._
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class ControlStructuresDemoUnitTest {
|
||||
@Test
|
||||
def givenTwoIntegers_whenGcdCalled_thenCorrectValueReturned() = {
|
||||
assertEquals(3, gcd(15, 27))
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenTwoIntegers_whenGcdIterCalled_thenCorrectValueReturned() = {
|
||||
assertEquals(3, gcdIter(15, 27))
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenTwoIntegers_whenRangeSumcalled_thenCorrectValueReturned() = {
|
||||
assertEquals(55, rangeSum(1, 10))
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenPositiveInteger_whenFactorialInvoked_thenCorrectValueReturned() = {
|
||||
assertEquals(720, factorial(6))
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenFactorialOf0Invoked_then1Returned() = {
|
||||
assertEquals(1, factorial(0))
|
||||
}
|
||||
|
||||
}
|
|
@ -1,30 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class EmployeeUnitTest {
|
||||
|
||||
@Test
|
||||
def whenEmployeeSalaryIncremented_thenCorrectSalary() = {
|
||||
val employee = new Employee("John Doe", 1000)
|
||||
employee.incrementSalary()
|
||||
assertEquals(1020, employee.salary)
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenEmployee_whenToStringCalled_thenCorrectStringReturned() = {
|
||||
val employee = new Employee("John Doe", 1000)
|
||||
assertEquals("Employee(name=John Doe, salary=1000)", employee.toString)
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenEmployeeWithTrait_whenToStringCalled_thenCorrectStringReturned() = {
|
||||
val employee =
|
||||
new Employee("John Doe", 1000) with UpperCasePrinter
|
||||
assertEquals("EMPLOYEE(NAME=JOHN DOE, SALARY=1000)", employee.toString)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
|
||||
class HigherOrderFunctionsExamplesUnitTest {
|
||||
|
||||
@Test
|
||||
def whenCallingMapWithAnonymousFunction_thenTransformationIsApplied() = {
|
||||
val expected = Seq("sir Alex Ferguson", "sir Bobby Charlton", "sir Frank Lampard")
|
||||
|
||||
val names = Seq("Alex Ferguson", "Bobby Charlton", "Frank Lampard")
|
||||
val sirNames = names.map(name => "sir " + name)
|
||||
|
||||
assertEquals(expected, sirNames)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenCallingMapWithDefined_thenTransformationIsApplied() = {
|
||||
val expected = Seq("sir Alex Ferguson", "sir Bobby Charlton", "sir Frank Lampard")
|
||||
|
||||
val names = Seq("Alex Ferguson", "Bobby Charlton", "Frank Lampard")
|
||||
|
||||
def prefixWithSir(name: String) = "sir " + name
|
||||
val sirNames = names.map(prefixWithSir)
|
||||
|
||||
assertEquals(expected, sirNames)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenCallingFilter_thenUnecessaryElementsAreRemoved() = {
|
||||
val expected = Seq("John O'Shea", "John Hartson")
|
||||
|
||||
val names = Seq("John O'Shea", "Aiden McGeady", "John Hartson")
|
||||
val johns = names.filter(name => name.matches("^John .*"))
|
||||
|
||||
assertEquals(expected, johns)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenCallingReduce_thenProperSumIsCalculated() = {
|
||||
val expected = 2750
|
||||
|
||||
val earnings = Seq(1000, 1300, 450)
|
||||
val sumEarnings = earnings.reduce((acc, x) => acc + x)
|
||||
|
||||
assertEquals(expected, sumEarnings)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenCallingFold_thenNumberOfWordsShouldBeCalculated() = {
|
||||
val expected = 6
|
||||
|
||||
val strings = Seq("bunch of words", "just me", "it")
|
||||
val sumEarnings = strings.foldLeft(0)((acc, x) => acc + x.split(" ").size)
|
||||
|
||||
assertEquals(expected, sumEarnings)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenCallingOwnHigherOrderFunction_thenProperFunctionIsReturned() = {
|
||||
def mathOperation(name: String): (Int, Int) => Int = (x: Int, y: Int) => {
|
||||
name match {
|
||||
case "addition" => x + y
|
||||
case "multiplication" => x * y
|
||||
case "division" => x/y
|
||||
case "subtraction" => x - y
|
||||
}
|
||||
}
|
||||
|
||||
def add: (Int, Int) => Int = mathOperation("addition")
|
||||
def mul: (Int, Int) => Int = mathOperation("multiplication")
|
||||
def div: (Int, Int) => Int = mathOperation("division")
|
||||
def sub: (Int, Int) => Int = mathOperation("subtraction")
|
||||
|
||||
assertEquals(15, add(10, 5))
|
||||
assertEquals(50, mul(10, 5))
|
||||
assertEquals(2, div(10, 5))
|
||||
assertEquals(5, sub(10, 5))
|
||||
}
|
||||
}
|
|
@ -1,48 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
import com.baeldung.scala.HigherOrderFunctions.mapReduce
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class HigherOrderFunctionsUnitTest {
|
||||
|
||||
@Test
|
||||
def whenCalledWithSumAndSquareFunctions_thenCorrectValueReturned() = {
|
||||
def square(x : Int) = x * x
|
||||
|
||||
def sum(x : Int, y : Int) = x + y
|
||||
|
||||
def sumSquares(a : Int, b : Int) =
|
||||
mapReduce(sum, 0, square, a, b)
|
||||
|
||||
assertEquals(385, sumSquares(1, 10))
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenComputingSumOfSquaresWithAnonymousFunctions_thenCorrectValueReturned() = {
|
||||
def sumSquares(a : Int, b : Int) =
|
||||
mapReduce((x, y) => x + y, 0, x => x * x, a, b)
|
||||
|
||||
assertEquals(385, sumSquares(1, 10))
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenCurriedFunctions_whenInvoked_thenCorrectValueReturned() = {
|
||||
// a curried function
|
||||
def sum(f : Int => Int)(a : Int,
|
||||
b : Int) : Int =
|
||||
if (a > b) 0 else f(a) + sum(f)(a + 1, b)
|
||||
|
||||
// another curried function
|
||||
def mod(n : Int)(x : Int) = x % n
|
||||
|
||||
// application of a curried function
|
||||
assertEquals(1, mod(5)(6))
|
||||
|
||||
// partial application of curried function
|
||||
// trailing underscore is required to make function type explicit
|
||||
val sumMod5 = sum(mod(5)) _
|
||||
|
||||
assertEquals(10, sumMod5(6, 10))
|
||||
}
|
||||
}
|
|
@ -1,21 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Test
|
||||
|
||||
class IntSetUnitTest {
|
||||
|
||||
@Test
|
||||
def givenSetof1To10_whenContains11Called_thenFalse() = {
|
||||
|
||||
// Set up a set containing integers 1 to 10.
|
||||
val set1To10 =
|
||||
Range(1, 10)
|
||||
.foldLeft(new EmptyIntSet() : IntSet) {
|
||||
(x, y) => x incl y
|
||||
}
|
||||
|
||||
assertFalse(set1To10 contains 11)
|
||||
}
|
||||
|
||||
}
|
|
@ -1,208 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
import java.io.FileNotFoundException
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class PatternMatchingUnitTest {
|
||||
@Test
|
||||
def whenAMammalIsGivenToTheMatchExpression_ThenItsRecognizedAsMammal(): Unit = {
|
||||
val result = new PatternMatching().caseClassesPatternMatching(Mammal("Lion", fromSea = false))
|
||||
assertEquals("I'm a Lion, a kind of mammal. Am I from the sea? false", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenABirdIsGivenToTheMatchExpression_ThenItsRecognizedAsBird(): Unit = {
|
||||
val result = new PatternMatching().caseClassesPatternMatching(Bird("Pigeon"))
|
||||
assertEquals("I'm a Pigeon, a kind of bird", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAnUnkownAnimalIsGivenToTheMatchExpression_TheDefaultClauseIsUsed(): Unit = {
|
||||
val result = new PatternMatching().caseClassesPatternMatching(Fish("Tuna"))
|
||||
assertEquals("I'm an unknown animal", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenTheConstantZeroIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = {
|
||||
val result = new PatternMatching().constantsPatternMatching(0)
|
||||
assertEquals("I'm equal to zero", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenFourAndAHalfIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = {
|
||||
val result = new PatternMatching().constantsPatternMatching(4.5d)
|
||||
assertEquals("I'm a double", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenTheBooleanFalseIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = {
|
||||
val result = new PatternMatching().constantsPatternMatching(false)
|
||||
assertEquals("I'm the contrary of true", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAnUnkownConstantIsPassed_ThenTheDefaultPatternIsUsed(): Unit = {
|
||||
val result = new PatternMatching().constantsPatternMatching(true)
|
||||
assertEquals("I'm unknown and equal to true", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenASingleElementListIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = {
|
||||
val result = new PatternMatching().sequencesPatternMatching(List("String"))
|
||||
assertEquals("I'm a list with one element: String", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAMultipleElementsListIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = {
|
||||
val result = new PatternMatching().sequencesPatternMatching(List("Multiple", "Elements"))
|
||||
assertEquals("I'm a list with one or multiple elements: List(Multiple, Elements)", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAVectorBeginningWithOneAndTwoIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = {
|
||||
val result = new PatternMatching().sequencesPatternMatching(Vector(1, 2, 3))
|
||||
assertEquals("I'm a vector: Vector(1, 2, 3)", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenANotMatchingVectorIsPassed_ThenItShouldntMatchAndEnterTheDefaultClause(): Unit = {
|
||||
val result = new PatternMatching().sequencesPatternMatching(Vector(2, 1))
|
||||
assertEquals("I'm an unrecognized sequence. My value: Vector(2, 1)", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAnEmptyListIsPassed_ThenItShouldntMatchAndEnterTheDefaultClause(): Unit = {
|
||||
val result = new PatternMatching().sequencesPatternMatching(List())
|
||||
assertEquals("I'm an unrecognized sequence. My value: List()", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenATwoElementsTupleIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = {
|
||||
val result = new PatternMatching().tuplesPatternMatching(("First", "Second"))
|
||||
assertEquals("I'm a tuple with two elements: First & Second", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAThreeElementsTupleIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = {
|
||||
val result = new PatternMatching().tuplesPatternMatching(("First", "Second", "Third"))
|
||||
assertEquals("I'm a tuple with three elements: First & Second & Third", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAnoterKindOfTupleIsPassed_ThenItShouldntMatchAndReturnTheDefaultPattern(): Unit = {
|
||||
val result = new PatternMatching().tuplesPatternMatching(("First"))
|
||||
assertEquals("Unrecognized pattern. My value: First", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAStringConsistingOfNumericsOnlyIsPassed_ThenItShouldMatchTheNumericRegex(): Unit = {
|
||||
val result = new PatternMatching().regexPatterns("123")
|
||||
assertEquals("I'm a numeric with value 123", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAStringConsistignOfAlphabeticsOnlyIsPassed_ThenItShouldMatchTheAlphabeticRegex(): Unit = {
|
||||
val result = new PatternMatching().regexPatterns("abc")
|
||||
assertEquals("I'm an alphabetic with value abc", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAStringConsistignOfAlphanumericsOnlyIsPassed_ThenItShouldMatchTheAlphanumericRegex(): Unit = {
|
||||
val result = new PatternMatching().regexPatterns("abc123")
|
||||
assertEquals("I'm an alphanumeric with value abc123", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAnotherTypeOfStringIsPassed_ThenItShouldntMatchAndReturnTheDefaultPattern(): Unit = {
|
||||
val result = new PatternMatching().regexPatterns("abc_123")
|
||||
assertEquals("I contain other characters than alphanumerics. My value abc_123", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAFilledOptionIsPassed_ThenItShouldMatchTheSomeClause(): Unit = {
|
||||
val result = new PatternMatching().optionsPatternMatching(Option.apply("something"))
|
||||
assertEquals("I'm not an empty option. Value something", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAnEmptyOptionIsPassed_ThenItShouldMatchTheNoneClause(): Unit = {
|
||||
val result = new PatternMatching().optionsPatternMatching(Option.empty)
|
||||
assertEquals("I'm an empty option", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAListWithAcceptedSizeIsPassed_ThenThePositiveMessageIsSent(): Unit = {
|
||||
val result = new PatternMatching().patternGuards(List(1, 2), 3)
|
||||
assertEquals("List is of acceptable size", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAListWithAnUnacceptedSizeIsPassed_ThenTheNegativeMessageIsSent(): Unit = {
|
||||
val result = new PatternMatching().patternGuards(List(1, 2, 3, 4), 3)
|
||||
assertEquals("List has not an acceptable size", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAStringWithAcceptedSizeIsPassed_ThenThePositiveMessageIsSent(): Unit = {
|
||||
val result = new PatternMatching().patternGuards("OK", 3)
|
||||
assertEquals("String is of acceptable size", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAStringWithAnUnacceptedSizeIsPassed_ThenTheNegativeMessageIsSent(): Unit = {
|
||||
val result = new PatternMatching().patternGuards("Not OK", 3)
|
||||
assertEquals("String has not an acceptable size", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAnObjectWhichIsNotAListOrAStringIsPassed_thenTheDefaultClauseIsUsed(): Unit = {
|
||||
val result = new PatternMatching().patternGuards(1, 1)
|
||||
assertEquals("Input is neither a List or a String", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenACardSuitIsPassed_ThenTheCorrespondingMatchCaseClauseIsUsed(): Unit = {
|
||||
assertEquals("Card is spike", new PatternMatching().sealedClass(Spike()))
|
||||
assertEquals("Card is club", new PatternMatching().sealedClass(Club()))
|
||||
assertEquals("Card is heart", new PatternMatching().sealedClass(Heart()))
|
||||
assertEquals("Card is diamond", new PatternMatching().sealedClass(Diamond()))
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAnObjectWithExtractorIsPassed_ThenTheExtractedValueIsUsedInTheCaseClause(): Unit = {
|
||||
val person = Person("John Smith")
|
||||
val result = new PatternMatching().extractors(person)
|
||||
assertEquals("My initials are J. S.", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAnObjectWithExtractorIsPassed_AndTheValueIsEmpty_ThenTheDefaultCaseClauseIsUsed(): Unit = {
|
||||
val person = Person("")
|
||||
val result = new PatternMatching().extractors(person)
|
||||
assertEquals("Could not extract initials", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAListOfRandomElementsIsPassed_ThenOnlyTheIntegersBelowTenAreReturned(): Unit = {
|
||||
val input = List(1, 2, "5", 11, true)
|
||||
val result = new PatternMatching().closuresPatternMatching(input)
|
||||
assertEquals(List(1, 2), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenAnExceptionIsPassed_ThenTheCorrespondingMessageIsReturned(): Unit = {
|
||||
val pm = new PatternMatching()
|
||||
|
||||
val iae = new IllegalArgumentException()
|
||||
val re = new RuntimeException()
|
||||
val fnfe = new FileNotFoundException()
|
||||
|
||||
assertEquals("It's an IllegalArgumentException", pm.catchBlocksPatternMatching(iae))
|
||||
assertEquals("It's a RuntimeException", pm.catchBlocksPatternMatching(re))
|
||||
assertEquals("It's an unknown kind of exception", pm.catchBlocksPatternMatching(fnfe))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
package com.baeldung.scala
|
||||
|
||||
import com.baeldung.scala.Utils.{average, fibonacci, power, randomLessThan}
|
||||
import org.junit.Assert.{assertEquals, assertTrue}
|
||||
import org.junit.Test
|
||||
|
||||
class UtilsUnitTest {
|
||||
|
||||
@Test
|
||||
def whenAverageCalled_thenCorrectValueReturned(): Unit = {
|
||||
assertEquals(15.0, average(10, 20), 1e-5)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenRandomLessThanInvokedWithANumber_thenARandomLessThanItReturned: Unit = {
|
||||
val d = 0.1
|
||||
assertTrue(randomLessThan(d) < d)
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenPowerInvokedWith2And3_then8Returned: Unit = {
|
||||
assertEquals(8, power(2, 3))
|
||||
}
|
||||
|
||||
@Test
|
||||
def whenFibonacciCalled_thenCorrectValueReturned: Unit = {
|
||||
assertEquals(1, fibonacci(0))
|
||||
assertEquals(1, fibonacci(1))
|
||||
assertEquals(fibonacci(6),
|
||||
fibonacci(4) + fibonacci(5))
|
||||
}
|
||||
}
|
|
@ -1,73 +0,0 @@
|
|||
package com.baeldung.scala.regex
|
||||
|
||||
import org.junit.Test
|
||||
import org.junit.Assert.assertEquals
|
||||
|
||||
class RegexUnitTest {
|
||||
private val polishPostalCode = "([0-9]{2})\\-([0-9]{3})".r
|
||||
private val timestamp = "([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{3})".r
|
||||
private val timestampUnanchored = timestamp.unanchored
|
||||
|
||||
@Test
|
||||
def givenRegularExpression_whenCallingFindFirstIn_thenShouldFindCorrectMatches(): Unit = {
|
||||
val postCode = polishPostalCode.findFirstIn("Warsaw 01-011, Jerusalem Avenue")
|
||||
assertEquals(Some("01-011"), postCode)
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenRegularExpression_whenCallingFindFirstMatchIn_thenShouldFindCorrectMatches(): Unit = {
|
||||
val postCodes = polishPostalCode.findFirstMatchIn("Warsaw 01-011, Jerusalem Avenue")
|
||||
assertEquals(Some("011"), for (m <- postCodes) yield m.group(2))
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenRegularExpression_whenCallingFindAllIn_thenShouldFindCorrectMatches(): Unit = {
|
||||
val postCodes = polishPostalCode.findAllIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue")
|
||||
.toList
|
||||
assertEquals(List("01-011", "30-059"), postCodes)
|
||||
|
||||
polishPostalCode.findAllIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue")
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenRegularExpression_whenCallingFindAlMatchlIn_thenShouldFindCorrectMatches(): Unit = {
|
||||
val postCodes = polishPostalCode.findAllMatchIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue")
|
||||
.toList
|
||||
val postalDistricts = for (m <- postCodes) yield m.group(1)
|
||||
assertEquals(List("01", "30"), postalDistricts)
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenRegularExpression_whenExtractingValues_thenShouldExtractCorrectValues(): Unit = {
|
||||
val description = "11:34:01.411" match {
|
||||
case timestamp(hour, minutes, _, _) => s"It's $minutes minutes after $hour"
|
||||
}
|
||||
|
||||
assertEquals("It's 34 minutes after 11", description)
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenUnanchoredRegularExpression_whenExtractingValues_thenShouldExtractCorrectValues(): Unit = {
|
||||
val description = "Timestamp: 11:34:01.411 error appeared" match {
|
||||
case timestampUnanchored(hour, minutes, _, _) => s"It's $minutes minutes after $hour"
|
||||
}
|
||||
|
||||
assertEquals("It's 34 minutes after 11", description)
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenRegularExpression_whenCallingReplaceAllIn_thenShouldReplaceText(): Unit = {
|
||||
val minutes = timestamp.replaceAllIn("11:34:01.311", m => m.group(2))
|
||||
|
||||
assertEquals("34", minutes)
|
||||
}
|
||||
|
||||
@Test
|
||||
def givenRegularExpression_whenCallingReplaceAllInWithMatcher_thenShouldReplaceText(): Unit = {
|
||||
val secondsThatDayInTotal = timestamp.replaceAllIn("11:34:01.311", _ match {
|
||||
case timestamp(hours, minutes, seconds, _) => s"$hours-$minutes"
|
||||
})
|
||||
|
||||
assertEquals("11-34", secondsThatDayInTotal)
|
||||
}
|
||||
}
|
2
pom.xml
2
pom.xml
|
@ -394,7 +394,6 @@
|
|||
|
||||
<module>core-java-modules</module>
|
||||
<module>core-kotlin-modules</module>
|
||||
<module>core-scala</module>
|
||||
|
||||
<module>couchbase</module>
|
||||
<module>custom-pmd</module>
|
||||
|
@ -907,7 +906,6 @@
|
|||
|
||||
<module>core-java-modules</module>
|
||||
<module>core-kotlin-modules</module>
|
||||
<module>core-scala</module>
|
||||
|
||||
<module>couchbase</module>
|
||||
<module>custom-pmd</module>
|
||||
|
|
Loading…
Reference in New Issue