Posts in the “scala” category

A Scala shell script to move your mouse cursor

I’m currently trying to automate a GUI task, and as a part of that, one thing I need to do is move the mouse cursor.

In short, the solution I came up with was to write a Scala shell script that uses the Java Robot class to move the mouse. Here’s the source code for my script, which I named MoveMouse.sh:

How to center a window/frame with Scala Swing

To center a window/frame in a Scala Swing application, add this line to your frame definition:

peer.setLocationRelativeTo(null)

Here’s what this looks like in the top method definition inside a SimpleSwingApplication:

A By The Bay interview with Tim Perrett

By The Bay has a very interesting interview with Tim Perrett, whose resume includes leading Scala teams at Verizon, and being a founding board member of the Scala Center.

A few good quotes from him at the beginning of the article: “Unlike many people in our industry, I left school at a young age and did not attend university. My first job was actually working in a factory. My modus operandi is that hard work and dedication can overcome any problem ... humility is something that enables one to be open to the ideas of others. To conclude: Listen, be humble, and roll up your sleeves.”

Processing Scala command-line arguments with Argot, and passing command-line arguments through SBT

Argot is the name of a Scala library that lets you read command-line options/arguments from a Scala application. (Presumably it will work with Java and other JVM-based languages as well.)

I’m trying to use Argot with an application of mine named Cato, and when I had problems getting Argot to work -- and then needed to pass command-line arguments to my application through SBT -- I decided to write this quick little test code and article.

Scala - How to declare multiple variables on one line

I thought I’d have a little fun with Scala today, and show different ways to declare multiple variables on one line. These aren’t the most useful or common things to do, but they’re interesting, and I know I learned at least one thing while looking into this.

You can define multiple fields on one line, separated by commas, as long as they are all the same type and have the same value:

A milestone day

September 26, 2017 is a little bit of a celebration day for me. It’s the day I reached the “No new content” milestone of my book on Scala and functional programming. At this point I’ll keep editing the book contents, and I really need to work on its formatting, but I don’t have any plans to write any new lessons.

A Scala REST “get content” client function using Apache HttpClient

As quick post here today, if you need a Scala REST client function, the following source code should be able to work for you, or at least be a good starting point. I’ve been using it in several applications today, and the only thing I think it needs is the ability to set a connection timeout and socket timeout, and I share the code for that down below.

SBT: Example build.sbt variables/settings (from PPrint)

Because I think it’s often best to “learn by example,” I’ve become a connoisseur of SBT build.sbt examples, and this build.sbt file from Lihaoyi’s PPrint project demonstrates a lot of SBT variables:

val baseSettings = Seq(
    organization := "com.lihaoyi",
    name := "pprint",
    version := _root_.pprint.Constants.version,
    scalaVersion := "2.11.11",
    testFrameworks := Seq(new TestFramework("utest.runner.Framework")),
    publishTo := Some("releases"  at "https://oss.sonatype.org/service/local/staging/deploy/maven2"),
    crossScalaVersions := Seq("2.10.6", "2.11.11", "2.12.2"),
    scmInfo := Some(ScmInfo(
        browseUrl = url("https://github.com/lihaoyi/PPrint"),
        connection = "scm:git:git@github.com:lihaoyi/PPrint.git"
    )),
    homepage := Some(url("https://github.com/lihaoyi/PPrint")),
    licenses := Seq("MIT" -> url("http://www.opensource.org/licenses/mit-license.html")),
    developers += Developer(
        email = "haoyi.sg@gmail.com",
        id = "lihaoyi",
        name = "Li Haoyi",
        url = url("https://github.com/lihaoyi")
    )
)

baseSettings

lazy val pprint = crossProject.crossType(CrossType.Pure)
  .settings(
    baseSettings,
    scalacOptions ++= Seq(scalaBinaryVersion.value match {
      case x if x.startsWith("2.12") => "-target:jvm-1.8"
      case _ => "-target:jvm-1.7"
    }),
    libraryDependencies ++= Seq(
      "com.lihaoyi" %%% "fansi" % "0.2.4",
      "org.scala-lang" % "scala-reflect" % scalaVersion.value % Provided,
      "org.scala-lang" % "scala-compiler" % scalaVersion.value % Provided,
      "com.lihaoyi" %%% "sourcecode" % "0.1.3",
      "com.lihaoyi" %%% "utest" % "0.4.7" % Test,
      "com.chuusai" %%% "shapeless" % "2.3.2" % Test
    ),

    unmanagedSourceDirectories in Compile ++= {
      if (Set("2.11", "2.12", "2.13.0-M1").contains(scalaBinaryVersion.value))
        Seq(baseDirectory.value / ".." / "src" / "main" / "scala-2.10+")
      else
        Seq()
    } ,
    unmanagedSourceDirectories in Test ++= {
      if (Set("2.11", "2.12", "2.13.0-M1").contains(scalaBinaryVersion.value))
        Seq(baseDirectory.value / ".." / "src" / "test" / "scala-2.10+")
      else
        Seq()
    },
    sourceGenerators in Compile += Def.task {
      val dir = (sourceManaged in Compile).value
      val file = dir/"pprint"/"TPrintGen.scala"

      val typeGen = for(i <- 2 to 22) yield {
        val ts = (1 to i).map("T" + _).mkString(", ")
        val tsBounded = (1 to i).map("T" + _ + ": Type").mkString(", ")
        val tsGet = (1 to i).map("get[T" + _ + "](cfg)").mkString(" + \", \" + ")
        s"""
          implicit def F${i}TPrint[$tsBounded, R: Type] = make[($ts) => R](cfg =>
            "(" + $tsGet + ") => " + get[R](cfg)
          )
          implicit def T${i}TPrint[$tsBounded] = make[($ts)](cfg =>
            "(" + $tsGet + ")"
          )
        """
      }
      val output = s"""
        package pprint
        trait TPrintGen[Type[_], Cfg]{
          def make[T](f: Cfg => String): Type[T]
          def get[T: Type](cfg: Cfg): String
          implicit def F0TPrint[R: Type] = make[() => R](cfg => "() => " + get[R](cfg))
          implicit def F1TPrint[T1: Type, R: Type] = {
            make[T1 => R](cfg => get[T1](cfg) + " => " + get[R](cfg))
          }
          ${typeGen.mkString("\n")}
        }
      """.stripMargin
      IO.write(file, output)
      Seq(file)
    }.taskValue
  )

lazy val pprintJVM = pprint.jvm
lazy val pprintJS = pprint.js

lazy val readme = scalatex.ScalatexReadme(
    projectId = "readme",
    wd = file(""),
    url = "https://github.com/lihaoyi/pprint/tree/master",
    source = "Readme"
).settings(
    scalaVersion := "2.11.8",
    (unmanagedSources in Compile) += baseDirectory.value/".."/"project"/"Constants.scala"
)

Using a sonatype library with SBT

That build.sbt file includes so many variables/settings that I’m not going to try to name them all, but one thing to note is that he publishes his project to sonatype.org. If you want to use PPrint in your own SBT project, that means that you’ll need to include this line in your own build.sbt file:

resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"

That tells SBT to use that URL as another repository it should look in for dependencies you’re trying to include in your project.

What is the difference between Nil and List() in Scala?

Scala FAQ: What is the difference between Nil and List() in Scala?

Short answer: There isn’t any difference, as shown in the Scala REPL:

scala> Nil == List()
res0: Boolean = true

It’s more “idiomatic Scala” Scala to use Nil rather than List(). For instance, I wrote code like this last night using Nil in a Scala match/case expression: