Skip to content

Instantly share code, notes, and snippets.

View rupeshtr78's full-sized avatar

rupeshtr78 rupeshtr78

View GitHub Profile
package PlayGround
object ScalaCollectionsTransform {
val evens = List(2,4,6)
val odds = List(1,3,5)
val a = "foo bar baz"
val foo = "foo"
val bar = "bar"
val names = List("Al","Chistina","Kim")
val evens = List(2,4,6)
val odds = List(1,3,5)
val a = "foo bar baz"
val foo = "foo"
val bar = "bar"
val names = List("Al","Chistina","Kim")
val firstTen = (1 to 10).toList
val fiveToFifteen = (5 to 15).toList
//Filter
object Person {
def apply(fullName: String) = fullName
def unapply(fullName: String): Option[String] = {
if (!fullName.isEmpty)
Some(fullName.replaceAll("(?<=\\w)(\\w+)", "."))
else
None
}
}
@rupeshtr78
rupeshtr78 / VarianceWithBounds.scala
Last active October 29, 2020 00:57
VarianceWithBounds
class Super
class Sub extends Super
class SubSub extends Sub
class InvariantSubType[A]{
def method[B <: A](value :B) = value
}
val invariantSubType1 = new InvariantSubType[Sub]
val res1 = invariantSubType1.method(new SubSub)
class Super
class Sub extends Super
class SubSub extends Sub
class UpperBound[A <:Super](val value:A)
val test10:UpperBound[Super] = new UpperBound(new Super)
val test12:UpperBound[Sub] = new UpperBound(new Sub)
val test112:UpperBound[SubSub] = new UpperBound(new SubSub)
// Type classes (implicit objects)
def foo2[B, A<:B] (a:A,b:B) = print("OK")
class A;
class B;
implicit def a2b(a:A) = new B
foo2(new A, new B) // implicit conversion!
trait Thing
trait Vehicle extends Thing
class Car extends Vehicle
class Jeep extends Car
class Coupe extends Car
class Motorcycle extends Vehicle
class Vegetable
class Parking[A](val place: A)
abstract class Animal
class Dog(name:String) extends Animal
// if DOG <:Animal does List[Dog] <: List[Animal]
val laika = new Dog("Laika")
val lassie = new Dog("lassie")
val hachi = new Dog("hachi")
//Implicit Ordering
case class SalesClass(product:String, unitPrice:Double, qty:Int){
def totalPrice :Double = unitPrice * qty
}
object ProductSorting {
// Note that because `Ordering[A]` is not contravariant, the declaration
// Type conversions with implicit functions
// When a compiler sees a type that is not expected in the evaluation context
// then it will try to find an implicit function in the current scope
// that can produce the expected type.
implicit def int2Str(int: Int): String = s"$int is Implicit Converted to String"
val x:String = 42.toUpperCase()
println(x) // 42 IS IMPLICIT CONVERTED TO STRING