Skip to content

Instantly share code, notes, and snippets.

@knightpop
knightpop / Variance.java
Created July 12, 2017 17:41
Java Variance Test
package org.ktz.example.blog;
import java.util.ArrayList;
import java.util.List;
public class Variance {
public static void main(String[] args) {
String str = "";
Object obj = str;
val obj: Object = "Hello World!"
val listString: List[String] = List.empty
val listAny: List[Any] = listString
type List[+A] = scala.collection.immutable.List[A]
class Person(val name: String, val age: Int, val weight: Int)
object Person {
def apply(name: String, age: Int, weight: Int): Person = new Person(name, age, weight)
def unapply(arg: Person): Option[(String, Int, Int)] =
if(arg.age >= 20) Some(arg.name, arg.age, arg.weight)
else None
}
trait AuthService {
def isLogged(name: String): Boolean
}
class AuthServiceChar3 extends AuthService{
override def isLogged(name: String): Boolean = name.length == 3
}
class AuthServiceChar5 extends AuthService{
override def isLogged(name: String): Boolean = name.length == 5
import cats.data.Writer
def greetW(name: String, logged: Boolean): Writer[List[String], String] =
Writer(List("Compose a greeting"), {
val userName = if(logged) name else "User"
s"Hello $userName"
})
def isLoggedW(name: String): Writer[List[String], Boolean] =
Writer(List("Checking if user is logged in"), name.length == 3)
package org.example.ktz.blog
import cats.syntax.all._
import cats.instances.future._
import org.scalatest._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
def getSome(a: Int): Option[Int] = Some(a)
def getNone(a: Int): Option[Int] = None
def add(a: Int, b: Int): Int = a + b
val aOpt = getSome(1)
val bOpt = getSome(2)
implicit val optionInt: Option[Int] = Some(1)
implicit val optionBoolean: Option[Boolean] = Some(true)
def getImplicitOptionInt(implicit oInt: Option[Int]): Int = oInt.get
def getImplicitOptionBoolean(implicit oBoolean: Option[Boolean]): Boolean = oBoolean.get
getImplicitOptionInt
getImplicitOptionBoolean
def getImplicitlyOptionA[A: Option]: A = implicitly[Option[A]].get
implicit val string: String = "Hello"
implicit val boolean: Boolean = true
implicit val int: Int = 0
def getImplicitT[T](implicit t: T): T = t
getImplicitT[Int]
getImplicitT[String]
getImplicitT[Boolean]