Skip to content

Commit f06ad17

Browse files
author
Eugen
authored
Merge pull request #1 from Baeldung/task/BAEL-18214
BAEL-18214 Configure Build Environment for Scala
2 parents 353fdd5 + 2675ef1 commit f06ad17

17 files changed

+716
-0
lines changed

.gitignore

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,18 @@
11
*.class
22
*.log
3+
4+
# sbt specific
5+
.cache/
6+
.history/
7+
.lib/
8+
dist/*
9+
target/
10+
lib_managed/
11+
src_managed/
12+
project/boot/
13+
project/plugins/project/
14+
15+
# Scala-IDE specific
16+
.scala_dependencies
17+
.worksheet
18+
.idea

core-scala/README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
## Core Scala
2+
3+
This module contains articles about Scala's core features
4+
5+
### Relevant Articles:
6+
7+
- [Introduction to Scala](https://www.baeldung.com/scala-intro)

core-scala/build.sbt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
ThisBuild / scalaVersion := "2.12.7"
2+
ThisBuild / version := "1.0-SNAPSHOT"
3+
ThisBuild / organization := "com.baeldung"
4+
ThisBuild / organizationName := "core-scala"
5+
6+
lazy val root = (project in file("."))
7+
.settings(
8+
name := "core-scala",
9+
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % Test,
10+
libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % "test"
11+
)
12+

core-scala/project/build.properties

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
sbt.version=1.3.4
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.baeldung.scala
2+
3+
/**
4+
* Sample code demonstrating the various control structured.
5+
*
6+
* @author Chandra Prakash
7+
*
8+
*/
9+
object ControlStructuresDemo {
10+
def gcd(x : Int, y : Int) : Int = {
11+
if (y == 0) x else gcd(y, x % y)
12+
}
13+
14+
def gcdIter(x : Int, y : Int) : Int = {
15+
var a = x
16+
var b = y
17+
while (b > 0) {
18+
a = a % b
19+
val t = a
20+
a = b
21+
b = t
22+
}
23+
a
24+
}
25+
26+
def rangeSum(a : Int, b : Int) = {
27+
var sum = 0;
28+
for (i <- a to b) {
29+
sum += i
30+
}
31+
sum
32+
}
33+
34+
def factorial(a : Int) : Int = {
35+
var result = 1;
36+
var i = 1;
37+
do {
38+
result *= i
39+
i = i + 1
40+
} while (i <= a)
41+
result
42+
}
43+
44+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.baeldung.scala
2+
3+
/**
4+
* Sample Code demonstrating a class.
5+
*
6+
* @author Chandra Prakash
7+
*
8+
*/
9+
class Employee(val name : String,
10+
var salary : Int,
11+
annualIncrement : Int = 20) {
12+
13+
def incrementSalary() : Unit = {
14+
salary += annualIncrement
15+
}
16+
17+
override def toString =
18+
s"Employee(name=$name, salary=$salary)"
19+
}
20+
21+
/**
22+
* A Trait which will make the toString return upper case value.
23+
*/
24+
trait UpperCasePrinter {
25+
override def toString: String = super.toString toUpperCase
26+
}
27+
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
package com.baeldung.scala
2+
3+
object HelloWorld extends App {
4+
println("Hello World!")
5+
args foreach println
6+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.baeldung.scala
2+
3+
/**
4+
* Sample higher order functions.
5+
*
6+
* @author Chandra Prakash
7+
*
8+
*/
9+
object HigherOrderFunctions {
10+
11+
def mapReduce(r : (Int, Int) => Int,
12+
i : Int,
13+
m : Int => Int,
14+
a : Int, b : Int): Int = {
15+
def iter(a : Int, result : Int) : Int = {
16+
if (a > b) result
17+
else iter(a + 1, r(m(a), result))
18+
}
19+
iter(a, i)
20+
}
21+
22+
def whileLoop(condition : => Boolean)(body : => Unit) : Unit =
23+
if (condition) {
24+
body
25+
whileLoop(condition)(body)
26+
}
27+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.baeldung.scala
2+
3+
/**
4+
* An abstract class for set of integers and its implementation.
5+
*
6+
* @author Chandra Prakash
7+
*
8+
*/
9+
abstract class IntSet {
10+
// add an element to the set
11+
def incl(x : Int) : IntSet
12+
13+
// whether an element belongs to the set
14+
def contains(x : Int) : Boolean
15+
}
16+
17+
class EmptyIntSet extends IntSet {
18+
19+
def contains(x : Int) : Boolean = false
20+
21+
def incl(x : Int) =
22+
new NonEmptyIntSet(x, this)
23+
}
24+
25+
class NonEmptyIntSet(val head : Int, val tail : IntSet)
26+
extends IntSet {
27+
28+
def contains(x : Int) : Boolean =
29+
head == x || (tail contains x)
30+
31+
def incl(x : Int) : IntSet =
32+
if (this contains x) this
33+
else new NonEmptyIntSet(x, this)
34+
}
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
package com.baeldung.scala
2+
3+
// Case Class
4+
abstract class Animal
5+
6+
case class Mammal(name: String, fromSea: Boolean) extends Animal
7+
8+
case class Bird(name: String) extends Animal
9+
10+
case class Fish(name: String) extends Animal
11+
12+
// Sealed Class
13+
sealed abstract class CardSuit
14+
15+
case class Spike() extends CardSuit
16+
17+
case class Diamond() extends CardSuit
18+
19+
case class Heart() extends CardSuit
20+
21+
case class Club() extends CardSuit
22+
23+
object Person {
24+
def apply(fullName: String) = fullName
25+
26+
def unapply(fullName: String): Option[String] = {
27+
if (!fullName.isEmpty)
28+
Some(fullName.replaceAll("(?<=\\w)(\\w+)", "."))
29+
else
30+
None
31+
}
32+
}
33+
34+
class PatternMatching {
35+
36+
def caseClassesPatternMatching(animal: Animal): String = {
37+
animal match {
38+
case Mammal(name, fromSea) => s"I'm a $name, a kind of mammal. Am I from the sea? $fromSea"
39+
case Bird(name) => s"I'm a $name, a kind of bird"
40+
case _ => "I'm an unknown animal"
41+
}
42+
}
43+
44+
def constantsPatternMatching(constant: Any): String = {
45+
constant match {
46+
case 0 => "I'm equal to zero"
47+
case 4.5d => "I'm a double"
48+
case false => "I'm the contrary of true"
49+
case _ => s"I'm unknown and equal to $constant"
50+
}
51+
}
52+
53+
def sequencesPatternMatching(sequence: Any): String = {
54+
sequence match {
55+
case List(singleElement) => s"I'm a list with one element: $singleElement"
56+
case List(_, _*) => s"I'm a list with one or multiple elements: $sequence"
57+
case Vector(1, 2, _*) => s"I'm a vector: $sequence"
58+
case _ => s"I'm an unrecognized sequence. My value: $sequence"
59+
}
60+
}
61+
62+
def tuplesPatternMatching(tuple: Any): String = {
63+
tuple match {
64+
case (first, second) => s"I'm a tuple with two elements: $first & $second"
65+
case (first, second, third) => s"I'm a tuple with three elements: $first & $second & $third"
66+
case _ => s"Unrecognized pattern. My value: $tuple"
67+
}
68+
}
69+
70+
def typedPatternMatching(any: Any): String = {
71+
any match {
72+
case string: String => s"I'm a string. My value: $string"
73+
case integer: Int => s"I'm an integer. My value: $integer"
74+
case _ => s"I'm from an unknown type. My value: $any"
75+
}
76+
}
77+
78+
def regexPatterns(toMatch: String): String = {
79+
val numeric = """([0-9]+)""".r
80+
val alphabetic = """([a-zA-Z]+)""".r
81+
val alphanumeric = """([a-zA-Z0-9]+)""".r
82+
83+
toMatch match {
84+
case numeric(value) => s"I'm a numeric with value $value"
85+
case alphabetic(value) => s"I'm an alphabetic with value $value"
86+
case alphanumeric(value) => s"I'm an alphanumeric with value $value"
87+
case _ => s"I contain other characters than alphanumerics. My value $toMatch"
88+
}
89+
}
90+
91+
def optionsPatternMatching(option: Option[String]): String = {
92+
option match {
93+
case Some(value) => s"I'm not an empty option. Value $value"
94+
case None => "I'm an empty option"
95+
}
96+
}
97+
98+
def patternGuards(toMatch: Any, maxLength: Int): String = {
99+
toMatch match {
100+
case list: List[Any] if (list.size <= maxLength) => "List is of acceptable size"
101+
case list: List[Any] => "List has not an acceptable size"
102+
case string: String if (string.length <= maxLength) => "String is of acceptable size"
103+
case string: String => "String has not an acceptable size"
104+
case _ => "Input is neither a List or a String"
105+
}
106+
}
107+
108+
def sealedClass(cardSuit: CardSuit): String = {
109+
cardSuit match {
110+
case Spike() => "Card is spike"
111+
case Club() => "Card is club"
112+
case Heart() => "Card is heart"
113+
case Diamond() => "Card is diamond"
114+
}
115+
}
116+
117+
def extractors(person: Any): String = {
118+
person match {
119+
case Person(initials) => s"My initials are $initials"
120+
case _ => "Could not extract initials"
121+
}
122+
}
123+
124+
def closuresPatternMatching(list: List[Any]): List[Any] = {
125+
list.collect { case i: Int if (i < 10) => i }
126+
}
127+
128+
def catchBlocksPatternMatching(exception: Exception): String = {
129+
try {
130+
throw exception
131+
} catch {
132+
case ex: IllegalArgumentException => "It's an IllegalArgumentException"
133+
case ex: RuntimeException => "It's a RuntimeException"
134+
case _ => "It's an unknown kind of exception"
135+
}
136+
}
137+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.baeldung.scala
2+
3+
/**
4+
* Some utility methods.
5+
*
6+
* @author Chandra Prakash
7+
*
8+
*/
9+
object Utils {
10+
def average(x : Double, y : Double): Double = (x + y) / 2
11+
12+
def randomLessThan(d : Double): Double = {
13+
var random = 0d
14+
do {
15+
random = Math.random()
16+
} while (random >= d)
17+
random
18+
}
19+
20+
def power(x : Int, y : Int) : Int = {
21+
def powNested(i : Int, accumulator : Int) : Int = {
22+
if (i <= 0) accumulator
23+
else powNested(i - 1, x * accumulator)
24+
}
25+
powNested(y, 1)
26+
}
27+
28+
def fibonacci(n : Int) : Int = n match {
29+
case 0 | 1 => 1
30+
case x if x > 1 =>
31+
fibonacci(x - 1) + fibonacci(x - 2)
32+
}
33+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.baeldung.scala
2+
3+
import com.baeldung.scala.ControlStructuresDemo._
4+
import org.junit.Assert.assertEquals
5+
import org.junit.Test
6+
7+
class ControlStructuresDemoUnitTest {
8+
@Test
9+
def givenTwoIntegers_whenGcdCalled_thenCorrectValueReturned() = {
10+
assertEquals(3, gcd(15, 27))
11+
}
12+
13+
@Test
14+
def givenTwoIntegers_whenGcdIterCalled_thenCorrectValueReturned() = {
15+
assertEquals(3, gcdIter(15, 27))
16+
}
17+
18+
@Test
19+
def givenTwoIntegers_whenRangeSumcalled_thenCorrectValueReturned() = {
20+
assertEquals(55, rangeSum(1, 10))
21+
}
22+
23+
@Test
24+
def givenPositiveInteger_whenFactorialInvoked_thenCorrectValueReturned() = {
25+
assertEquals(720, factorial(6))
26+
}
27+
28+
@Test
29+
def whenFactorialOf0Invoked_then1Returned() = {
30+
assertEquals(1, factorial(0))
31+
}
32+
33+
}

0 commit comments

Comments
 (0)