core-scala: initial commit

This commit is contained in:
Swapan Pramanick 2018-08-09 02:07:23 +05:30
parent e35e84291e
commit d46873405a
21 changed files with 567 additions and 0 deletions

13
core-scala/build.gradle Normal file
View File

@ -0,0 +1,13 @@
apply plugin: 'scala'
repositories {
mavenCentral()
}
dependencies {
compile 'org.scala-lang:scala-library:2.12.6'
testCompile 'org.scalatest:scalatest_2.12:3.0.5'
testCompile 'junit:junit:4.12'
}

12
core-scala/build.sbt Normal file
View File

@ -0,0 +1,12 @@
import Dependencies._
lazy val root = (project in file(".")).
settings(
inThisBuild(List(
organization := "com.example",
scalaVersion := "2.12.6",
version := "0.1.0-SNAPSHOT"
)),
name := "core-scala",
libraryDependencies += scalaTest % Test
)

111
core-scala/pom.xml Normal file
View File

@ -0,0 +1,111 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-scala</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<encoding>UTF-8</encoding>
<scala.version>2.12.6</scala.version>
<scala.compat.version>2.12</scala.compat.version>
<spec2.version>4.2.0</spec2.version>
</properties>
<dependencies>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_${scala.compat.version}</artifactId>
<version>3.0.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.specs2</groupId>
<artifactId>specs2-core_${scala.compat.version}</artifactId>
<version>${spec2.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.specs2</groupId>
<artifactId>specs2-junit_${scala.compat.version}</artifactId>
<version>${spec2.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/scala</sourceDirectory>
<testSourceDirectory>src/test/scala</testSourceDirectory>
<plugins>
<plugin>
<!-- see http://davidb.github.com/scala-maven-plugin -->
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>3.3.2</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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.21.0</version>
<configuration>
<!-- Tests will be run with scalatest-maven-plugin instead -->
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.scalatest</groupId>
<artifactId>scalatest-maven-plugin</artifactId>
<version>2.0.0</version>
<configuration>
<reportsDirectory>${project.build.directory}/surefire-reports</reportsDirectory>
<junitxml>.</junitxml>
<filereports>TestSuiteReport.txt</filereports>
<!-- Comma separated list of JUnit test class names to execute -->
<jUnitClasses>samples.AppTest</jUnitClasses>
</configuration>
<executions>
<execution>
<id>test</id>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,5 @@
import sbt._
object Dependencies {
lazy val scalaTest = "org.scalatest" %% "scalatest" % "3.0.5"
}

View File

@ -0,0 +1 @@
sbt.version=1.1.6

View File

@ -0,0 +1,31 @@
package com.baeldung.examples
object ClassExamples extends App {
import java.time._
class Customer(val id:Int, val name:String, dob:LocalDate) {
private var _age = calculateAge(dob)
def age = _age // getter
def age_= (age:Int) = _age = age //setter
private def calculateAge(dob:LocalDate) = Period
.between(dob, LocalDate.now)
.getYears
//override def toString: String = s"(id:${id}, name:${name}, age:${age})"
}
val c = new Customer(1, "Varun Sharma", LocalDate.parse("1980-02-27"))
println(c)
case class Address(addressLn1:String, area:String, city:String, zip:String)
val address=Address("102, Raycon Lotus Apartment", "AECS Layout", "Bangalore", "560037")
val anotherAddress = address.copy(addressLn1="41/2, ITPL Road")
println(address)
println(anotherAddress)
}

View File

@ -0,0 +1,22 @@
package com.baeldung.examples
object CollectionExamples extends App {
val aList = List(5, 3, 9, 2) // create a list
val sortedAscList = aList.sorted // sort ascending
val sortedDescList = aList.sortWith(_ > _) // sort descending
val evenList = aList.filter(_%2 == 0) // filter on some condition
val mySet = Set(10, 20, 5) // create a set
val changedSet = mySet + 50 // add an element
println(changedSet)
val changedSet2 = mySet - 20 // remove an element
println(changedSet2)
val capitals = Map("Japan" -> "Tokyo",
"England" -> "London",
"India" -> "New Delhi") // create a map
val capitalOfJapan = capitals("Japan") // get from map
println(capitalOfJapan)
}

View File

@ -0,0 +1,19 @@
package com.baeldung.examples
object ExceptionHandlingExamples extends App {
import java.io._
def printLines(filename:String) = {
var reader:Option[BufferedReader] = None
try {
reader = Some(new BufferedReader(new FileReader(new File(filename))))
reader.get.lines().forEach(println(_))
} catch {
case e:FileNotFoundException => println(s"There was no file named ${filename}")
case e:Throwable => throw new Exception("Some error occurred", e)
} finally {
if (reader.isDefined) reader.get.close()
}
}
printLines("test.txt")
}

View File

@ -0,0 +1,17 @@
package com.baeldung.examples
object FirstClassFunctionExamples extends App {
def sum(x:Double, y:Double, f:Double => Double) = f(x) + f(y)
println(sum(3, 4, x => x*x)) // returns 25.0
println(sum(3, 4, x => x*x*x)) // returns 91.0
println(sum(3, 4, Math.pow(_, 2))) // returns 25.0
def max(first:Int, second:Int) = if (first > second) first else second
println(max(10, -2))
}

View File

@ -0,0 +1,39 @@
package com.baeldung.examples
object LoopAndCalculationExamples extends App {
import CalculationUtils._
println(sumWithWhile(Array(10, 20, 30)))
println(sumWithFor(Array(10, 20, 30)))
println(checkEvenOdd((1 to 10).toArray).toList)
println(filterEvens((1 to 10).toArray).toList)
}
object CalculationUtils {
def sumWithWhile(values:Array[Int]) = {
var sum = 0
var i = 0
while ( i < values.length) {
sum += values(i)
i+=1
}
sum
}
def sumWithFor(values:Array[Int]) = {
var sum = 0
for (i <- values) {
sum += i
}
sum
}
def checkEvenOdd(values:Array[Int]) = {
for (i <- values) yield if (i%2 == 0) "Even" else "Odd"
}
def filterEvens(values:Array[Int]) =
for (i <- values if i%2 == 0)
yield i
}

View File

@ -0,0 +1,15 @@
package com.baeldung.examples
/**
* @author ${user.name}
*/
object MyApp {
def foo(x : Array[String]) = x.foldLeft("")((a,b) => a + b)
def main(args : Array[String]) {
println( "Hello World!" )
println("Number of arguments passed:" + args.length)
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.examples
object ObjectExamples extends App {
import java.time._
class Customer(val id:Int, val name:String, private var _age:Int) {
def age = this._age
def age_= (age:Int) = _age = age
}
object Customer {
def apply(id:Int, name:String, age:Int) = new Customer(id, name, age)
def apply(id:Int, name:String, dob:LocalDate) = {
val p = Period.between(dob, LocalDate.now)
new Customer(id, name, p.getYears)
}
}
val c = Customer(1, "Varun Sharma", LocalDate.parse("1980-02-27"))
c.age = 20
println(c.age)
}

View File

@ -0,0 +1,12 @@
package com.baeldung.examples
object OptionExample extends App {
def minimumEvenNumber(data:Array[Int]) = {
val evens = data.filter(_%2 == 0)
if (evens.isEmpty) None else Some(evens.min)
}
val minEven = minimumEvenNumber(Array(21, 3, 11, 7)).getOrElse(0)
println(minEven)
}

View File

@ -0,0 +1,22 @@
package com.baeldung.examples
object PatternMatchingExample extends App {
abstract class Item
case class Book(title:String, author:String, price:Double) extends Item
case class MusicCD(title:String, genre:String, price:Double) extends Item
def describe(item:Item) = item match {
case b:Book if b.price > 1000 => println(s"The book ${b.title} is expensive")
case b:Book => println(s"The book ${b.title} is written by ${b.author}.")
case MusicCD(title, "Jazz", _) => println(s"This is a CD of Jazz music.")
case _ => println("Unknown Item")
}
describe(Book("Half Girlfriend", "Chetan Bhagat", 100))
}

View File

@ -0,0 +1,23 @@
package com.baeldung.examples
import java.io._
object TraitExample extends App {
trait Loggable {
val logger:PrintStream
def getPrefix():String
def log(message:String) = logger.println(s"[${getPrefix()}]:${message}")
}
object CustomerService extends Loggable {
override val logger = System.out
override def getPrefix(): String = "CustomerService"
def retrieve(id:String) = {
log(s"Retrieve with id ${id} called")
// Code to retrieve Customer from DB
}
}
CustomerService.retrieve("C100")
}

View File

@ -0,0 +1,18 @@
package com.baeldung.examples
object TupleExamples extends App {
val empSal:(String, Int) = ("David", 10000)
def getMaxMinSalary(empSal:Array[(String, Int)]) = {
val minEmpSal = empSal.minBy(empSal => empSal._2)
val maxEmpSal = empSal.maxBy(empSal => empSal._2)
(maxEmpSal._2, minEmpSal._2)
}
val empSalArr = Array(("David", 12000), ("Maria", 15000),
("Elisa", 11000), ("Adam", 8000))
val (maxSalary, minSalary) = getMaxMinSalary(empSalArr)
println("Max Salary: " + maxSalary + " and Min Salary: " + minSalary)
}

View File

@ -0,0 +1,24 @@
package com.baeldung.examples
object VariableDeclaration extends App {
val x:Int = 0
var friend:String = "David"
lazy val greet = "Hello" + friend
val data = Array(2, 4, 5)
printHelloWorld()
println(sum(10, 20))
def printHelloWorld():Unit = {
println("Hello World")
}
def sum(x:Int, y:Int) = x + y
def sayGreeting(to:String, greet:String="Hi", message:String = "How are you?") = println(greet + " " + to + ", " + message)
sayGreeting(to="David", message="How are you doing?")
sayGreeting(greet="Hello", to="Maria")
}

View File

@ -0,0 +1,17 @@
package samples
import org.junit._
import Assert._
@Test
class AppTest {
@Test
def testOK() = assertTrue(true)
// @Test
// def testKO() = assertTrue(false)
}

View File

@ -0,0 +1,108 @@
/*
* Copyright 2001-2009 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package samples
/*
ScalaTest facilitates different styles of testing by providing traits you can mix
together to get the behavior and syntax you prefer. A few examples are
included here. For more information, visit:
http://www.scalatest.org/
One way to use ScalaTest is to help make JUnit or TestNG tests more
clear and concise. Here's an example:
*/
import scala.collection._
import org.scalatest.Assertions
import org.junit.Test
class StackSuite extends Assertions {
@Test def stackShouldPopValuesIinLastInFirstOutOrder() {
val stack = new mutable.ArrayStack[Int]
stack.push(1)
stack.push(2)
assert(stack.pop() === 2)
assert(stack.pop() === 1)
}
@Test def stackShouldThrowRuntimeExceptionIfAnEmptyArrayStackIsPopped() {
val emptyStack = new mutable.ArrayStack[String]
intercept[RuntimeException] {
emptyStack.pop()
}
}
}
/*
Here's an example of a FunSuite with Matchers mixed in:
*/
import org.scalatest.FunSuite
import org.scalatest.Matchers
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class ListSuite extends FunSuite with Matchers {
test("An empty list should be empty") {
List() should be ('empty)
Nil should be ('empty)
}
test("A non-empty list should not be empty") {
List(1, 2, 3) should not be ('empty)
List("fee", "fie", "foe", "fum") should not be ('empty)
}
test("A list's length should equal the number of elements it contains") {
List() should have length (0)
List(1, 2) should have length (2)
List("fee", "fie", "foe", "fum") should have length (4)
}
}
/*
ScalaTest also supports the behavior-driven development style, in which you
combine tests with text that specifies the behavior being tested. Here's
an example whose text output when run looks like:
A Map
- should only contain keys and values that were added to it
- should report its size as the number of key/value pairs it contains
*/
import org.scalatest.FunSpec
class ExampleSpec extends FunSpec {
describe("An ArrayStack") {
it("should pop values in last-in-first-out order") {
val stack = new mutable.ArrayStack[Int]
stack.push(1)
stack.push(2)
assert(stack.pop() === 2)
assert(stack.pop() === 1)
}
it("should throw RuntimeException if an empty array stack is popped") {
val emptyStack = new mutable.ArrayStack[Int]
intercept[RuntimeException] {
emptyStack.pop()
}
}
}
}

View File

@ -0,0 +1,31 @@
package samples
import org.junit.runner.RunWith
import org.specs2.mutable._
import org.specs2.runner._
/**
* Sample specification.
*
* This specification can be executed with: scala -cp <your classpath=""> ${package}.SpecsTest
* Or using maven: mvn test
*
* For more information on how to write or run specifications, please visit:
* http://etorreborre.github.com/specs2/guide/org.specs2.guide.Runners.html
*
*/
@RunWith(classOf[JUnitRunner])
class MySpecTest extends Specification {
"The 'Hello world' string" should {
"contain 11 characters" in {
"Hello world" must have size(11)
}
"start with 'Hello'" in {
"Hello world" must startWith("Hello")
}
"end with 'world'" in {
"Hello world" must endWith("world")
}
}
}

4
core-scala/test.txt Normal file
View File

@ -0,0 +1,4 @@
Hi,
This is the lines
from the test file.
Thanks.