Scala: Create a random number between a min and max value (a range)
As a quick note, here’s a Scala function to generate a random integer value that will be in between the input min and max values:
As a quick note, here’s a Scala function to generate a random integer value that will be in between the input min and max values:
As a brief note today, here’s a little Scala application that reads an HTML file, parses it with JSoup, and then I select all of the elements with the CSS selector shown. After that, I use some Scala goodness to read all the text values of those elements, see if there is a "W"
(win) or "L"
(loss) character there, convert that to a Seq[Boolean]
, and then generated an ASCII Sparkline chart based on those results.
Note that the desired CSS selectors look like this in the HTML:
Creating an ASCII version of a Sparkline chart — or Win/Loss chart — in Scala turned out to take just a few lines of code, as shown in this photo.
As I mentioned previously, the Neotype library is a nice improvement over the verbose Scala 3 opaque type feature. This little example begins to show how much better Neotype is than opaque types, where opaque types require more boilerplate to implement less functionality:
//> using scala "3"
//> using lib "io.github.kitlangton::neotype::0.3.0"
import neotype.*
// [1] Opaque type:
opaque type Username = String
object Username:
def apply(value: String): Username = value
// [2] Neotype:
object Password extends Newtype[String]:
override inline def validate(input: String): Boolean =
input.nonEmpty && input.length > 2
@main def NeotypeTests =
val u = Username("Alvin")
println(u)
val p = Password("12")
println(p)
Sometimes when you’re working with Scala and want to do things in a functional way, the solution isn’t always clear. For instance, I wanted to write a database query using plain old SQL and JDBC, so to do that, I needed to work with iterating over a ResultSet
.
Specifically, I’m writing a little “password manager” application, and for one function I just wanted to return list of all the “app names” stored in the database, where an “app” is something like Gmail, Facebook, Twitter, or any other application or service that requires a username and password.
At the time of this writing there aren’t many examples of the Scala Exception
object allCatch
method to be found, so I thought I’d share some examples here.
In each example I first show the "success" case, and then show the "failure" case. Other than that, I won’t explain these, but hopefully seeing them in the REPL will be enough to get you pointed in the right direction:
If you’d like to get started working with the Scala ZIO functional programming (FP) library, here are two little ZIO 101 and ZIO 102 “Hello, world” examples that you can run with Scala CLI and Scala 3.
First, here’s a complete ZIO “Hello, world” example that shows everything you need to get started using ZIO with Scala CLI:
As a brief note today, I was starting to look at a free JSON REST web service that to get stock information, and their JSON for a single stock looks like this:
{
"Global Quote": {
"01. symbol": "IBM",
"02. open": "182.4300",
"03. high": "182.8000",
"04. low": "180.5700",
"05. price": "181.5800",
"06. volume": "3037990",
"07. latest trading day": "2024-04-19",
"08. previous close": "181.4700",
"09. change": "0.1100",
"10. change percent": "0.0606%"
}
}
I just wrote the following ZIO 2 question about how to use ZIO.cond
to a friend, and got the answer shown. I’ve also added in my own comments where they make sense.
Hey, I’m trying to understand why my ZIO failWithMsgEffect
doesn’t seem to get run in the following code example?
I have learned that there are better ways to handle this, but I’ve found that if I don’t understand something like this, it will come back to bite me later. Here’s the code:
As a little ZIO 2 example with Scala 3, here’s some code that starts to show how to use ZIO.timeout
along with ZIO.attempt
while accessing an internet URL with Scala’s Source.fromURL
.
Basically all I’m doing is:
Source.fromURL
,ZIO##timeout
Here’s the code:
Scala date FAQ: How do I format dates (DateTimeFormatter
, LocalDate
) in Scala? That is, when using Scala (2 or 3), how do I format dates, such as for printing them out in a desired format?
The solution is to use the java.time.format.DateTimeFormatter class. It provides three types of formatters for printing date/time values:
Scala date/time FAQ: How do I create new date and time instances with Scala? Specifically, using Scala, how do I create new date and time instances using the Date and Time API that was introduced with Java 8.
Using the Java 8 API and newer — Java 11, 14, 17, etc. — you can create new dates, times, and date/time values. The table below provides a description of some of the new Java date/time classes you’ll use (from the java.time Javadoc), all of which work in the ISO-8601 calendar system.
Scala date/time FAQ: How do I get the current date and time in Scala?
The following code demonstrates how to get the current time in Scala, and then further shows how to get other information, such as the current minute, using the Java SimpleDateFormat class:
Scala FAQ: When you write a Scala for
expression or for
loop, when do you use an =
symbol and when do you use the <-
symbol in the for
block area?
As a brief note, here are a few examples of how to implement left-trim and right-trim on strings in Scala:
def ltrim(s: String) = s.replaceAll("^\\s+", "") def rtrim(s: String) = s.replaceAll("\\s+$", "")
If I ever write a Scala StringUtils
class, I’ll be sure to include those functions in that class.
Scala exec FAQ: How do I execute external system commands in Scala?
When it comes to executing external system commands, Scala is a dramatic improvement over Java. The operators Scala makes available are much more like Perl or Ruby, and the operators themselves are consistent with traditional shell commands, and are therefore easy to remember. Let's take a look at a few examples.
Scala/Java/Kotlin String
FAQ: How do I replace left brackets and right brackets — i.e., the [
and ]
characters — in a String
when using methods like replaceFirst
and replaceAll
?
If you’re using Scala, Java, Kotlin, or other JVM languages, and need to replace left or right brackets in a String
, I found the following solution, which seems to work well with String
methods like replaceFirst
and replaceAll
.
As a brief note today, here are several examples of the Scala 3 while
loop syntax.
First, here are some one-line examples. This is the preferred syntax, using the while/do keywords.
while i >= 0 do i = f(i)