From d46873405a67addfaa69aa7855b37af9c4a3df14 Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Thu, 9 Aug 2018 02:07:23 +0530 Subject: [PATCH] core-scala: initial commit --- core-scala/build.gradle | 13 ++ core-scala/build.sbt | 12 ++ core-scala/pom.xml | 111 ++++++++++++++++++ core-scala/project/Dependencies.scala | 5 + core-scala/project/build.properties | 1 + .../com/baeldung/examples/ClassExamples.scala | 31 +++++ .../examples/CollectionExamples.scala | 22 ++++ .../examples/ExceptionHandlingExamples.scala | 19 +++ .../examples/FirstClassFunctionExamples.scala | 17 +++ .../examples/LoopAndCalculationExamples.scala | 39 ++++++ .../scala/com/baeldung/examples/MyApp.scala | 15 +++ .../baeldung/examples/ObjectExamples.scala | 23 ++++ .../com/baeldung/examples/OptionExample.scala | 12 ++ .../examples/PatternMatchingExample.scala | 22 ++++ .../com/baeldung/examples/TraitExample.scala | 23 ++++ .../com/baeldung/examples/TupleExamples.scala | 18 +++ .../examples/VariableDeclaration.scala | 24 ++++ core-scala/src/test/scala/samples/junit.scala | 17 +++ .../src/test/scala/samples/scalatest.scala | 108 +++++++++++++++++ core-scala/src/test/scala/samples/specs.scala | 31 +++++ core-scala/test.txt | 4 + 21 files changed, 567 insertions(+) create mode 100644 core-scala/build.gradle create mode 100644 core-scala/build.sbt create mode 100644 core-scala/pom.xml create mode 100644 core-scala/project/Dependencies.scala create mode 100644 core-scala/project/build.properties create mode 100644 core-scala/src/main/scala/com/baeldung/examples/ClassExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/CollectionExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/ExceptionHandlingExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/FirstClassFunctionExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/LoopAndCalculationExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/MyApp.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/ObjectExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/OptionExample.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/PatternMatchingExample.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/TraitExample.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/TupleExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/VariableDeclaration.scala create mode 100644 core-scala/src/test/scala/samples/junit.scala create mode 100644 core-scala/src/test/scala/samples/scalatest.scala create mode 100644 core-scala/src/test/scala/samples/specs.scala create mode 100644 core-scala/test.txt diff --git a/core-scala/build.gradle b/core-scala/build.gradle new file mode 100644 index 0000000000..05b5d5c55a --- /dev/null +++ b/core-scala/build.gradle @@ -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' +} + + diff --git a/core-scala/build.sbt b/core-scala/build.sbt new file mode 100644 index 0000000000..1e21f71d39 --- /dev/null +++ b/core-scala/build.sbt @@ -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 + ) diff --git a/core-scala/pom.xml b/core-scala/pom.xml new file mode 100644 index 0000000000..76b6ee0d22 --- /dev/null +++ b/core-scala/pom.xml @@ -0,0 +1,111 @@ + + 4.0.0 + core-scala + 1.0-SNAPSHOT + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 1.8 + 1.8 + UTF-8 + 2.12.6 + 2.12 + 4.2.0 + + + + + org.scala-lang + scala-library + ${scala.version} + + + + + junit + junit + 4.12 + test + + + org.scalatest + scalatest_${scala.compat.version} + 3.0.5 + test + + + org.specs2 + specs2-core_${scala.compat.version} + ${spec2.version} + test + + + org.specs2 + specs2-junit_${scala.compat.version} + ${spec2.version} + test + + + + + src/main/scala + src/test/scala + + + + net.alchim31.maven + scala-maven-plugin + 3.3.2 + + + + compile + testCompile + + + + -dependencyfile + ${project.build.directory}/.scala_dependencies + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.21.0 + + + true + + + + org.scalatest + scalatest-maven-plugin + 2.0.0 + + ${project.build.directory}/surefire-reports + . + TestSuiteReport.txt + + samples.AppTest + + + + test + + test + + + + + + + diff --git a/core-scala/project/Dependencies.scala b/core-scala/project/Dependencies.scala new file mode 100644 index 0000000000..558929deb6 --- /dev/null +++ b/core-scala/project/Dependencies.scala @@ -0,0 +1,5 @@ +import sbt._ + +object Dependencies { + lazy val scalaTest = "org.scalatest" %% "scalatest" % "3.0.5" +} diff --git a/core-scala/project/build.properties b/core-scala/project/build.properties new file mode 100644 index 0000000000..d6e35076cc --- /dev/null +++ b/core-scala/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.1.6 diff --git a/core-scala/src/main/scala/com/baeldung/examples/ClassExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/ClassExamples.scala new file mode 100644 index 0000000000..75a37e2bab --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/ClassExamples.scala @@ -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) + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/CollectionExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/CollectionExamples.scala new file mode 100644 index 0000000000..1602516067 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/CollectionExamples.scala @@ -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) + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/ExceptionHandlingExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/ExceptionHandlingExamples.scala new file mode 100644 index 0000000000..16ec7ffdf4 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/ExceptionHandlingExamples.scala @@ -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") + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/FirstClassFunctionExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/FirstClassFunctionExamples.scala new file mode 100644 index 0000000000..bf925f59c7 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/FirstClassFunctionExamples.scala @@ -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)) + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/LoopAndCalculationExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/LoopAndCalculationExamples.scala new file mode 100644 index 0000000000..17091c715d --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/LoopAndCalculationExamples.scala @@ -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 + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/MyApp.scala b/core-scala/src/main/scala/com/baeldung/examples/MyApp.scala new file mode 100644 index 0000000000..d0861a8727 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/MyApp.scala @@ -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) + } + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/ObjectExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/ObjectExamples.scala new file mode 100644 index 0000000000..29db276ebd --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/ObjectExamples.scala @@ -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) + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/OptionExample.scala b/core-scala/src/main/scala/com/baeldung/examples/OptionExample.scala new file mode 100644 index 0000000000..b0d49af758 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/OptionExample.scala @@ -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) +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/PatternMatchingExample.scala b/core-scala/src/main/scala/com/baeldung/examples/PatternMatchingExample.scala new file mode 100644 index 0000000000..d476bed60b --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/PatternMatchingExample.scala @@ -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)) +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/TraitExample.scala b/core-scala/src/main/scala/com/baeldung/examples/TraitExample.scala new file mode 100644 index 0000000000..0775a2bac2 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/TraitExample.scala @@ -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") + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/TupleExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/TupleExamples.scala new file mode 100644 index 0000000000..e9ffbd0aca --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/TupleExamples.scala @@ -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) + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/VariableDeclaration.scala b/core-scala/src/main/scala/com/baeldung/examples/VariableDeclaration.scala new file mode 100644 index 0000000000..6050b4f908 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/VariableDeclaration.scala @@ -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") + +} diff --git a/core-scala/src/test/scala/samples/junit.scala b/core-scala/src/test/scala/samples/junit.scala new file mode 100644 index 0000000000..89513d5bbc --- /dev/null +++ b/core-scala/src/test/scala/samples/junit.scala @@ -0,0 +1,17 @@ +package samples + +import org.junit._ +import Assert._ + +@Test +class AppTest { + + @Test + def testOK() = assertTrue(true) + +// @Test +// def testKO() = assertTrue(false) + +} + + diff --git a/core-scala/src/test/scala/samples/scalatest.scala b/core-scala/src/test/scala/samples/scalatest.scala new file mode 100644 index 0000000000..bd10412199 --- /dev/null +++ b/core-scala/src/test/scala/samples/scalatest.scala @@ -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() + } + } + } +} diff --git a/core-scala/src/test/scala/samples/specs.scala b/core-scala/src/test/scala/samples/specs.scala new file mode 100644 index 0000000000..9e4dfe93bb --- /dev/null +++ b/core-scala/src/test/scala/samples/specs.scala @@ -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 ${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") + } + } +} diff --git a/core-scala/test.txt b/core-scala/test.txt new file mode 100644 index 0000000000..da431d2039 --- /dev/null +++ b/core-scala/test.txt @@ -0,0 +1,4 @@ +Hi, +This is the lines +from the test file. +Thanks. \ No newline at end of file