/r/scala
Information Regarding Scala:
Platforms
Community
Coding Tools:
IDES / Programming Environments
Build Tools
Code Formatting / Linting
Free Books, Tutorials and Guides:
Non-free Books:
Advanced!:
Free Scala Courses:
Scala Conferences:
Podcasts:
Scala Jobs:
Scala Libraries:
Web Development and Microservices
Web Front End (Scala.js)
Database Access
Functional Programming
Concurrency / Parallelism
Mathematics
Distributed Computing
Blockchain
Monitoring/instrumentation:
Miscellaneous:
Open Source Applications written in Scala
Want your library here? Message the moderators!
Related Communities:
Blogs/Periodicals:
/r/scala
https://github.com/getkyo/kyo/releases/tag/v0.15.0
This is yet another packed #Kyo release! ✨
Task
, similar to kyo-zio
and kyo-cats
.kyo-scheduler
, kyo-core
, kyo-direct
, kyo-sttp
, and kyo-combinators
. Kyo's adaptive scheduler and high-performance async primitives can now be used in Native!kyo-stm
module, including a TMap data structure. The implementation uses a fine-grained read/write commit-time lock mechanism designed to reduce retry likelihood and allow transactions to commit concurrently in more scenarios.kyo-prelude
providing MTL-like state isolation with rollback capabilities. Integrates with Async
APIs and powers the STM
effect's retry handling.kyo-core
.kyo-test
now provides a stronger integration with zio-test
, enabling users to mix zio/kyo effects in the same test suite. This unlocks the use of Gen
and check
.Full Changelog: v0.14.1...v0.15.0
Hi everyone,
I’m a beginner in Scala and have recently started working with Option. While I understand its purpose, I often find it makes debugging quite challenging, and I wonder if I might be using it incorrectly.
For instance, when chaining operations like this:
Option.map(myFunc).map(myFunc2)...
If one of the steps in the chain results in None, it’s hard to figure out at which step the None was returned. This becomes an issue when I need to debug and fix the specific function responsible for returning None.
In scenarios like this, it feels like Option might not be the right choice. Would it make more sense to use traditional try-catch blocks in such cases? Or is there a better approach to handle this with Option itself?
Any advice or insights would be greatly appreciated!
inline given [T](using Mirror.Of[T]): JsonCodec[T] = DeriveJsonCodec.gen[T]
The Scala Center is happy to announce that for the fourth year in a row, we are supporting the Scala Community’s participation in the annual Advent of Code challenge for 2024!
https://www.scala-lang.org/blog/2024/12/02/advent-of-code-announce.html
You can read sample solutions and explanations, add links to your own solutions, and discuss in a dedicated channel on the Scala Discord.
I have a vscode devcontainer set up with the metals extension:
{
"name": "Scala 3",
"image": "mcr.microsoft.com/devcontainers/base:ubuntu-24.04",
"customizations": {
"vscode": {
"extensions": [
"scala-lang.scala",
"scalameta.metals",
"ms-azuretools.vscode-docker"
],
"settings": {
"terminal.integrated.defaultProfile.linux": "bash",
"terminal.integrated.profiles.linux": {
"bash": {
"path": "/bin/bash",
"icon": "terminal-bash",
"args": [
"-l"
]
}
}
}
}
},
"postCreateCommand": "curl -sSLf https://scala-cli.virtuslab.org/get | sh"
}
I'm using the metals-supplied java. My build is recognized, I can compile and run everything using the extension, works fine.
However Metals Doctor gives the following errors:
### Bloop error:
java.nio.file.AccessDeniedException: <WORKSPACE>/.bloop/root/bloop-internal-classes/classes-Metals-HsMr1fnNR_2eD9OaUxRViA==-Eu0RI9mWSx-cJ0_8vTep-g==/CreditCard.class
Does anyone have suggestions on what could be happening here? I added all permissions to the .bloop directory recursively for all users.
How do I make yay
not invocable if Endpoint
doesn't have SSE
requirement?
The `Requirements` must be contravariant, as it's how it's defined in Tapir.
https://scastie.scala-lang.org/7NycMA4iTUm44CD5L44NGA
Edit: I've also posted to Tapir forum: https://softwaremill.community/t/introducing-serversentevents-capability-failing-to-achieve-type-safety/460
Scala raylib, how to plot a moving circle ? A demo in Dlang, https://gitlab.com/alaindevos/dlangtut/-/blob/master/dub/69_raylib/source/app.d
def validateInt(s: String): Validation[String, Int] =
Validation(s.toInt).mapError(_.getMessage)
def validateAge(age: Int): Validation[String, Int] =
Validation.fromPredicateWith(s"Age $age was less than zero")(age)(_ >= 0)
def validateIntAndAge(): Validation[String, Unit] =
for {
_ <- validateInt("A")
_ <- validateAge(-20)
} yield ()
This is a modified code from the example in the docs. The problem with this is it will short-circuit when an error occurs. I want to be able to have a list of all the errors instead of only having one.
How can I achieve this?
Following program has a type error. Any advice is welkom.
import scalafx.Includes._
import scalafx.scene.control._
import scalafx.scene.layout.HBox
import scalafx.event.ActionEvent
import scalafx.application.JFXApp3
import scalafx.scene.Scene
import scalafx.scene.layout.StackPane
import scalafx.scene.paint.Color
import scalafx.scene.shape.Circle
import scalafx.scene.canvas.{Canvas, GraphicsContext}
var mycircle :StackPane =
var width = 500;
var height = 500;
var canvas = new Canvas(width, height);
var gc = canvas.getGraphicsContext2D;
// Draw a simple line
for (x<-0 until width)
var y = ((Math.sin(x * 0.02) * 100 + height / 2)).toInt;
gc.setFill(javafx.scene.paint.Color.RED);
gc.fillRect(x, y, 1, 1);
var root = new StackPane(canvas); // Error : Found scalafx.scene.Canvas required javafx.scene.StackPane
root
object MyProgram extends JFXApp3 {
override def start(): Unit = {
stage = new JFXApp3.PrimaryStage {
title = "MyProgram"
scene = new Scene(400,400) {
fill = Color.White
content = List(mycircle)
}}}}
I need to create a black canvas of 200 by 200 pixels. And i need to have one function , plot a blue pixel at coordinates (100,100). If i can plot one pixel, i can plot anything.
Cfr, https://www.reddit.com/r/fsharp/comments/1h2g7pv/simple_graphics_api/
Hey,
The short post I made about "FP in Scala" course got much more likes than I anticipated. I'm very happy but because there were only two short comments, I'd like to ask you for some feedback.
There is a lot of education materials about Scala and FP online, and there are some courses at universities (although, not that much) and lectures at meetups and conferences, etc. What do you think people like me - who make talks, videos, and lectures - could do more or better? More courses for beginners? More deep dives into specific technologies? And in what form: YouTube videos? Coursera courses? Free talks on video platforms, like streams on YouTube, Twitch, or Discord? Offline lectures, like on meetups? Or maybe you have a feeling there is enough material on the internet but it's not organized well enough?
Give me your thoughts. Whatever comes to your mind.
I am using "Coursier" and get the following warning. I did "cs update scala3" , "cs update sbt"
scala3 ./target/scala-3.3.4/myapplication_3-1.jar
[warning] MainGenericRunner class is deprecated since Scala 3.5.0, and Scala CLI features will not work.
[warning] Please be sure to update to the Scala CLI launcher to use the new features.
[warning] It appears that your Coursier-based Scala installation is misconfigured.
[warning] To update to the new Scala CLI runner, please update (coursier, cs) commands first before re-installing scala.
[warning] Check the Scala 3.5.0 release notes to troubleshoot your installation.
What does this warning means. And how to get rid of it.
Is the style of the following program, a union of a string and an int good?
package alain
import scala.Array
import scala.annotation.targetName
import scala.util.chaining.*
import scala.annotation.tailrec
import scala.language.postfixOps
extension [A](a: A) @targetName("|>") def |>[B](f: A => B): B = a pipe f
object CubeCalculator:
def cube(x: Int): Int = x * x * x
class MyInt(_myint: Int):
var myInt: Int = _myint
class MyString(_mystring: String):
var myString: String = _mystring
type StringOrInt = MyString | MyInt
class CStringOrInt(_si: StringOrInt):
var si:StringOrInt = _si
extension (x: CStringOrInt) @targetName("printstringorint") def printstringorint: Unit =
x.si match
case y:MyInt => printf("%d\n", y.myInt)
case y: MyString => printf("%s\n", y.myString)
@main private def main(args: String*): Int =
var si1:CStringOrInt=CStringOrInt(MyInt(5))
var si2:CStringOrInt=CStringOrInt(MyString("five"))
si1.printstringorint
si2.printstringorint
0
The links are fine, both files get downloaded when links are set into search engine. Java is not even able to read the responseCode.
import scala.io.Source
object Test extends App:
val urlGood = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=demo"
val urlBad = "https://api.nasdaq.com/api/nordic/instruments/FI0008900212/chart/download?assetClass=INDEXES&fromDate=2024-11-20&toDate=2024-11-27"
def get(url: String) =
val source = Source.fromURL(url) //ININITE LOOP HERE
source.getLines().foreach(println)
source.close()
get(urlGood) // correctly prints all of the data
get(urlBad) // this is the last line of code that is executed, the prosess doesn't stop and files are not downloaded.
Hey,
Just a heads-up: I'm from the IntelliJ Scala Plugin team at JetBrains. I have just wrapped up a "Functional Programming in Scala" course at Czech Technical University in Prague. It took 4.5h (3 x 1.5h long lectures), it covered the core concepts and included coded examples in IntelliJ IDEA with the Scala Plugin. There'll be similar events in the future, on other universities, and for meetup groups, both online and offline, so let me know if you'd like to organize one :)
More info about the course: https://plugins.jetbrains.com/plugin/23833-functional-programming-in-scala
Hey all,
Usually I manage to figure things out, but here I'm a bit lost. I assume I should probably check what's going on in Wireshark but my mind is fried so far.
Here's what's going on:
I have a mock application in Http4s using DigestAuth, this was working fine until this morning when I added TLS to the mix and with using TLS my authentication fails.
Code is not great, but is just me thinkering around:
package p1
import cats.effect.{ExitCode, IO, IOApp, Resource}
import com.comcast.ip4s.{ipv4, port}
import fs2.io.net.Network
import fs2.io.net.tls.TLSParameters
import org.http4s.{AuthedRoutes, Entity, HttpRoutes, Request, Response}
import org.http4s.dsl.io.*
import org.http4s.ember.server.EmberServerBuilder
import io.circe.generic.semiauto.*
import io.circe.{Decoder, Encoder}
import org.http4s.circe.CirceEntityCodec.*
import org.http4s.server.middleware.authentication.DigestAuth
import org.http4s.server.{AuthMiddleware, Router, Server}
import org.typelevel.log4cats.slf4j.Slf4jFactory
import java.io.File
import java.security.KeyStore
import java.time.LocalDateTime
import javax.net.ssl.{KeyManagerFactory, SSLContext}
import scala.util.{Failure, Success, Try}
// Models
trait Inbound
case class MessageTypeA(
message
: String) extends Inbound
case class MessageTypeB(
timestamp
: String,
pos
: Int,
flag
: Boolean) extends Inbound
trait Outbound
case class SuccessInfo(
timestamp
: String,
message
: String)
case class OutboundSuccess(
info
: SuccessInfo) extends Outbound
case class FailureReason(
timestamp
: String,
reason
: String)
case class OutboundFailure(
reason
: FailureReason) extends Outbound
object Codecs {
import cats.syntax.functor._
// Enables the `widen` method
implicit val
messageTypeADecoder
: Decoder[MessageTypeA] =
deriveDecoder
implicit val
messageTypeBDecoder
: Decoder[MessageTypeB] =
deriveDecoder
implicit val
inboundDecoder
: Decoder[Inbound] = Decoder[MessageTypeA].widen.or(Decoder[MessageTypeB].widen)
implicit val
successInfoEncoder
: Encoder[SuccessInfo] =
deriveEncoder
implicit val
outboundSuccessEncoder
: Encoder[OutboundSuccess] =
deriveEncoder
implicit val
failureReasonEncoder
: Encoder[FailureReason] =
deriveEncoder
implicit val
outboundFailureEncoder
: Encoder[OutboundFailure] =
deriveEncoder
}
case class User(
id
: Long,
name
: String)
val passMap: Map[String, (Long, String, String)] = Map[String, (Long, String, String)](
"jurgen" -> (1L, "127.0.0.1", "pw123")
)
object DigestAuthImpl{
import org.http4s.server.middleware.authentication.DigestAuth.Md5HashedAuthStore
private val
ha1
= (username: String, realm: String, pw: String) => {
Md5HashedAuthStore.
precomputeHash
[IO](username, realm, pw)
}
private val
funcPass
: String => IO[Option[(User, String)]] = (usr_name: String) =>
val cleaned = usr_name.toLowerCase
passMap.get(cleaned) match
case Some((id,realm, pw)) =>
ha1
(cleaned,realm, pw).flatMap(hash => IO(Some(User(id, cleaned), hash)))
case None => IO(None)
def middleware: String => IO[AuthMiddleware[IO, User]] = (realm: String) =>
DigestAuth.
applyF
[IO, User](realm, Md5HashedAuthStore(
funcPass
))
}
object SimpleTcpServer extends IOApp with com.typesafe.scalalogging.LazyLogging{
import Codecs._
private def digestRoutes = AuthedRoutes.
of
[User, IO]{
case req@
GET -> Root /
"login" as user =>
Ok
(s"Welcome $user")
}
private val
digestService
= DigestAuthImpl.
middleware
("127.0.0.1").map(wrapper => wrapper(
digestRoutes
))
def routes: HttpRoutes[IO] = HttpRoutes.
of
[IO] {
case req @
POST -> Root /
"proc" =>
req
.as[Inbound]
.map {
case MessageTypeA(message) =>
OutboundSuccess(SuccessInfo(LocalDateTime.
now
.toString, s"Msg received: $message"))
case MessageTypeB(timestamp, pos, flag) =>
OutboundSuccess(SuccessInfo(LocalDateTime.
now
.toString, s"Flag received: $timestamp, $pos, $flag"))
}
.handleError(e => OutboundFailure(FailureReason(LocalDateTime.
now
.toString, e.getMessage)))
.flatMap {
case success: OutboundSuccess =>
Ok
(success)
case failure: OutboundFailure =>
BadRequest
(failure)
}
}
private val
router
: Resource[IO, HttpRoutes[IO]] =
for {
secureRoutes <-
Resource
.
eval
(
digestService
)
// Lift IO[HttpRoutes[IO]] into Resource
combinedRoutes = Router(
"/" ->
routes
,
"/s" -> secureRoutes
)
} yield combinedRoutes
val
SSLContext
: Option[SSLContext] = {
Try {
val ksFile = new File("src/main/resources/sec/ks/myserver.jks")
val keystorePass = "hokkokeystore".toCharArray
val keyStore = KeyStore.
getInstance
(ksFile, keystorePass)
val keyManagerFactory = KeyManagerFactory.
getInstance
(KeyManagerFactory.
getDefaultAlgorithm
)
keyManagerFactory.init(keyStore, keystorePass)
val sslContext = javax.net.ssl.SSLContext.
getInstance
("TLS")
sslContext.init(keyManagerFactory.getKeyManagers, null, null)
sslContext
} match
case Failure(exception) =>
println
(exception.getMessage)
None
case Success(value) => Some(value)
}
private val
tls
= Network[IO].tlsContext.fromSSLContext(
SSLContext
.orNull)
private val
serverResource
: Resource[IO, Server] = {
implicit val logging: Slf4jFactory[IO] = Slf4jFactory.
create
[IO]
logger
.info("Server starting")
def logHeadersMiddleware(routes: HttpRoutes[IO]): HttpRoutes[IO] = HttpRoutes.
of
[IO] {
case req@_ =>
// Log the headers of every request
logger
.info(s"Received request with headers: ${req.
headers
.
headers
.mkString("\n")}")
routes(req).getOrElseF(
InternalServerError
())
// Forward the request to the next route in the chain
}
router
.flatMap { app =>
val logged = logHeadersMiddleware(app)
EmberServerBuilder
.
default
[IO]
.withHost(ipv4"0.0.0.0")
.withPort(port"8080")
.withTLS(
tls
, TLSParameters.
Default
)
.withHttp2
.withConnectionErrorHandler{ case error =>
IO.
println
(error.getMessage).as(Response(status =
BadRequest
, entity = Entity.
utf8String
(error.getMessage)))
}
.withHttpApp(logged.orNotFound)
.build
}
}
override def run(args: List[String]): IO[ExitCode] =
serverResource
.useForever
}
Hi, so I'm pretty new to the "functional programming" paradigm, but I'm really interested, and I have a question about what is considered a referentially transparent function. I'm not sure if this is the best place to ask, but several posts I’ve found discussing this topic have been on this subreddit, so that's why I'm posting here. If this is the wrong place, I just ask for guidance on the correct one.
I am coming from TypeScript, and that is the language I will use for my examples (again, I apologize, but I don’t actually know Scala, haha), but hopefully, the ideas will be pretty language-agnostic, so I’m hoping it will be fine.
I have read several definitions stating that a referentially transparent function is one that has no side effects, or that, in essence, you can replace the value it evaluates to with the result of the function execution without changing anything. Bartosz Milewski, in his Category Theory class, puts it as: "Can it be memoized without changing anything?"
Basically, if you were to rewrite a program with the evaluated result instead of the function call, would it be equivalent? If yes, it is referentially transparent.
So, for example, the following function is referentially transparent:
const add5 = (x: number) => {
return x + 5
}
As you can store the value of the call without any difference:
Example 1
const result1 = add5(3) // <- stores 8
const result2 = add5(3) + add5(3)
Is functionally identical to:
Example 2
const result1 = add5(3) // <- stores 8
const result2 = result1 + result1
If we were to instead declare add5
like this:
const add5 = (x: number) => {
console.log("adding 5")
return x + 5
}
Then the function is no longer referentially transparent since, in Example 1, we would see the log 3 times, whereas in Example 2, we would only see the log once.
That is pretty clear to me. My question is: what happens if we define the function like this?
const add5 = (x: number) => {
return x + process.env.FIVE
}
Then what do we call this? Is it still referentially transparent? It passes all the mentioned tests (unless you call reading the value from the environment a side effect, but that, to me, seems like a stretch). Yet, it is clearly referencing something outside of the function definition, and under different contexts, it will return different results with the same parameters.
But in none of the definitions I have read about "referential transparency" does it mention the fact that the function should evaluate to the same thing under the same set of inputs.
I’m not sure. To me, reading about referential transparency in linguistics, it seems like a referentially transparent statement is one that does not assume anything about context. Everything it references is clear and stated, such that if you replace one part of the statement with an equivalent one, the whole statement is equivalent.
That, to me, seems like the essence of the term: do not assume context; everything must be clearly laid out.
But maybe I am misunderstanding, and referential transparency in programming is not directly related to that.
If that’s the case, then I ask: is there a term to refer to functions that do not assume anything? Like, anything the function uses is either defined inside the function or passed as a parameter, such that regardless of context or place of execution, the same function call with the same set of parameters will always evaluate to the same result?
Maybe "Pure Function" is the correct term but I seen referential transparency and being a pure function being called the same, so I'm not sure hahaha
sealed trait NonEmptyMap[K, V]
object NonEmptyMap {
infix def combine[K, V](
s: SingleEntryMap[K, V],
s2: SingleEntryMap[K, V]
): MultipleEntryMap[K, V] = ???
infix def combine[K, V](
s: SingleEntryMap[K, V],
m: MultipleEntryMap[K, V]
): MultipleEntryMap[K, V] = ???
infix def combine[K, V](
m: MultipleEntryMap[K, V],
s: SingleEntryMap[K, V]
): MultipleEntryMap[K, V] = ???
infix def combine[K, V](
m: MultipleEntryMap[K, V],
m2: MultipleEntryMap[K, V]
): MultipleEntryMap[K, V] = ???
}
SingleEntryMap
and MultipleEntryMap
are custom implementations of NonEmptyMap
and I want to combine them together.
I want to know how you would structure the combine API?
Edit: If theres a way to incorporate cats, I'd like to know.