Created
January 12, 2023 15:55
-
-
Save Janiczek/686cbd20faa3f6cb83cb4632179f6f46 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package example | |
| object Hello { | |
| def main(args: Array[String]): Unit = | |
| println("Hello") | |
| // 1 implicit conversions | |
| // NEVER USE THIS | |
| { | |
| import scala.language.implicitConversions | |
| case class MyThing(n: Int) | |
| case class TheirThing(n: Int) | |
| implicit def convertThings(theirThing: TheirThing): MyThing = | |
| MyThing(theirThing.n) | |
| def incMyThing(myThing: MyThing): MyThing = { | |
| //myThing.copy(n = myThing.n + 1) | |
| MyThing(myThing.n + 1) | |
| } | |
| val x: MyThing = incMyThing(MyThing(2)) | |
| val y = incMyThing(TheirThing(2)) | |
| // ^^^^^^^^^^ | |
| } | |
| // 2 implicit extensions | |
| implicit class RichString(string: String) { | |
| def happy(): String = string ++ " LOL" | |
| } | |
| "hello".happy() // -> "hello LOL" | |
| // 3 implicit parameters | |
| case class Metadata(string: String) | |
| implicit val metadata = Metadata("abc") | |
| def addOneWithMetadata(n: Int, metadata: Metadata): Int = n + 1 | |
| addOneWithMetadata(5, metadata) | |
| def addOneWithMetadataImplicit(n: Int)(implicit metadata: Metadata): Int = n + 1 | |
| addOneWithMetadataImplicit(5) | |
| // 4 typeclasses | |
| trait Show[A] { | |
| def show(a: A): String | |
| } | |
| def show[A](a: A)(implicit showInstance: Show[A]): String = | |
| showInstance.show(a) | |
| def show2[A: Show](a: A): String = { | |
| implicitly[Show[A]].show(a) | |
| } | |
| implicit val stringShow: Show[String] = new Show[String] { | |
| override def show(a: String): String = a | |
| } | |
| implicit val intShow: Show[Int] = new Show[Int] { | |
| override def show(a: Int): String = a.toString | |
| } | |
| show("abc") | |
| show2(123) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment