Skip to content

BAEL-18214 Configure Build Environment for Scala #1

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 2 commits into from
Dec 24, 2019
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
16 changes: 16 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,18 @@
*.class
*.log

# sbt specific
.cache/
.history/
.lib/
dist/*
target/
lib_managed/
src_managed/
project/boot/
project/plugins/project/

# Scala-IDE specific
.scala_dependencies
.worksheet
.idea
7 changes: 7 additions & 0 deletions core-scala/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
## Core Scala

This module contains articles about Scala's core features

### Relevant Articles:

- [Introduction to Scala](https://www.baeldung.com/scala-intro)
12 changes: 12 additions & 0 deletions core-scala/build.sbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
ThisBuild / scalaVersion := "2.12.7"
ThisBuild / version := "1.0-SNAPSHOT"
ThisBuild / organization := "com.baeldung"
ThisBuild / organizationName := "core-scala"

lazy val root = (project in file("."))
.settings(
name := "core-scala",
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % Test,
libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % "test"
)

1 change: 1 addition & 0 deletions core-scala/project/build.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sbt.version=1.3.4
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
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
}

}
27 changes: 27 additions & 0 deletions core-scala/src/main/scala/com/baeldung/scala/Employee.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
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
}

6 changes: 6 additions & 0 deletions core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.baeldung.scala

object HelloWorld extends App {
println("Hello World!")
args foreach println
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
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)
}
}
34 changes: 34 additions & 0 deletions core-scala/src/main/scala/com/baeldung/scala/IntSet.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
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)
}
137 changes: 137 additions & 0 deletions core-scala/src/main/scala/com/baeldung/scala/PatternMatching.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
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"
}
}
}
33 changes: 33 additions & 0 deletions core-scala/src/main/scala/com/baeldung/scala/Utils.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
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)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
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))
}

}
Loading