I want you to use Scala as Better Java for the time being

Introduction

It's been about two years since I started using Scala. I love Scala, so I recommend it to the engineers around me, but it seems that there is a reluctance to say, "Functional language? It seems difficult and Java is not good?" Sure, it's hard to get all the features of Scala, but if you just want to know how good Scala is, you don't need to understand "functional" from the beginning. So here are some of the features of Scala that I find appealing to Java engineers.

Make the most of Java assets

Scala has a package manager called sbt that can be used with any library distributed by Maven as well. You can also coexist Scala and Java in the source code in your project. In other words, you don't have to replace the source code all at once, and you can say, "Let's try only the new features we will create with Scala."

case class

Create a Coin (coin) class with price (amount) and ʻunit(unit). For 100 yen coins, use it likenew Coin (100.0," Yen ")`. If you use case class, you can write as follows.

Coin.scala


case class Coin(price: Double, unit: String)

The equivalent code in Java is as follows. (To be exact, it overrides hashCode, toString, copy, etc., but it will be too long, so I will omit it.)

JavaCoin.java


public class JavaCoin {

    public final double price;
    public final String unit;

    public JavaCoin(double price, String unit) {
        this.price = price;
        this.unit = unit;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof JavaCoin) {
            JavaCoin another = (JavaCoin) obj;
            return this.price == another.price && this.unit.equals(another.unit);
        }
        return false;
    }

}

It's overwhelmingly short. I think shortness is justice.

Most elements are expressions

The elements that make up a program are ** expressions ** and ** statements **. By definition, the one that returns the value is an expression, and everything else is a statement. In Java, ʻif, for, switch`, etc. are statements, but in Scala these are all expressions. A concrete example will be explained later.

switch is powerful

Add the following method to the Coin class. A method that aligns ʻunitwithDollar`.

Coin.scala


  def toDollar: Coin =
    this match {
      case Coin(_, "Dollar") => this
      case Coin(_price, "Cent") => Coin(_price * 0.01, "Dollar")
      case Coin(_price, "Yen") => Coin(_price * 0.088, "Dollar")
    }

match is switch in Scala. As mentioned above, with case class, you can match properties and bind them to variables. (Actually, you should use polymorphism, but I won't use it this time because it will be complicated.) Also, I didn't write return, but in Scala the result of the expression is the return value without writing anything. In Scala, match is an expression, so it's a return value.

Operator override

Add the following method to the Coin class. A method that adds two Coins.

Coin.scala


  def +(another: Coin): Coin =
    if (this.unit == another.unit)
      Coin(this.price + another.price, this.unit)
    else
      this.toDollar + another.toDollar

If ʻunitis the same, it is added as it is, and if it is different, it is added in line with" Dollar "`. It can be used as an operator as follows.

  println(
    Coin(1, "Dollar")
      + Coin(10, "Cent")
      + Coin(25, "Cent")
      + Coin(100, "Yen")
      + Coin(500, "Yen")
  )
  // Coin(54.15,Dollar)

Has no state (does not reassign)

As you've read so far, you'll notice that Scala basically doesn't ** reassign **. It is the same as the Java final declaration. You might ask, "Why don't you use final in Java? ", But it's important to note that in Scala most language specifications, standard libraries, and third-party libraries follow this rule. Not reassigning can be rephrased as having no state. If you don't have a state, the return value of the function will be determined only by the arguments, which makes it simpler to think about. There are many benefits, such as not having to look at the values of variables in the debugger or write test cases that assume the state. It's a roundabout explanation, but you should be able to realize the strength of this rule while using it. (Actually, this item puts one foot into the functional concept, but I explained it because I think it is the most important.)

in conclusion

It's been a long time, but thank you for reading. There are still a lot of things I would like to introduce, but I'm not sure, so I'll stop here. More and more companies are adopting Scala these days, and I hope this article helps.

Whole source code

Coin.scala


case class Coin(price: Double, unit: String) {

  def toDollar: Coin =
    this match {
      case Coin(_, "Dollar") => this
      case Coin(_price, "Cent") => Coin(_price * 0.01, "Dollar")
      case Coin(_price, "Yen") => Coin(_price * 0.088, "Dollar")
    }

  def +(another: Coin): Coin =
    if (this.unit == another.unit)
      Coin(this.price + another.price, this.unit)
    else
      this.toDollar + another.toDollar

}

object Coin extends App {

  println(
    Coin(1, "Dollar")
      + Coin(10, "Cent")
      + Coin(25, "Cent")
      + Coin(100, "Yen")
      + Coin(500, "Yen")
  )
  // Coin(54.15,Dollar)

}

Recommended Posts

I want you to use Scala as Better Java for the time being
Use Java external library for the time being
Glassfish tuning list that I want to keep for the time being
I want you to use Enum # name () for the Key of SharedPreference
I want to use the Java 8 DateTime API slowly (now)
Java14 came out, so I tried record for the time being
Introduction to java for the first time # 2
Java12 came out, so I tried the switch expression for the time being
When you want to use the method outside
Run Dataflow, Java, streaming for the time being
I want to use Combine in UIKit as well.
[Java] I want to calculate the difference from the date
I want to use ES2015 in Java too! → (´ ・ ω ・ `)
Command to try using Docker for the time being
I translated [Clone method for Java arrays] as the Clone method in Java arrays.
I want to use screen sharing on the login screen on Ubuntu 18
[Java] Use ResolverStyle.LENIENT to handle the date and time nicely
I want to return multiple return values for the input argument
I want to simplify the conditional if-else statement in Java
I want to use Java Applet easily on the command line without using an IDE
Use JLine when you want to handle keystrokes on the console character by character in Java
I want to use FormObject well
I want to create a chat screen for the Swift chat app!
I want to return to the previous screen with kotlin and java!
The story of Collectors.groupingBy that I want to keep for posterity
If you want to change the Java development environment from Eclipse
[Java] I want to perform distinct with the key in the object
If you want to mock a method in RSpec, you should use the allow method for mock and the singleton method.
A memo when you want to clear the time part of the calendar
[Java] How to use the File class
I want to display the number of orders for today using datetime.
[Java] How to use the hasNext function
About the procedure for java to work
I want to use DBViewer with Eclipse 2018-12! !!
[Java] How to use the toString () method
eclipse I definitely want you to use Transcendental Recommended Shortcut Key (Windows)
[Processing × Java] How to use the loop
(Limited to Java 7 or later) I want you to compare objects in Objects.equals
[Java] How to set the Date time to 00:00:00
[Processing × Java] How to use the class
I want to stop Java updates altogether
I want to get the IP address when connecting to Wi-Fi in Java
Learning for the first time java [Introduction]
[Processing × Java] How to use the function
I want to use @Autowired in Servlet
I went to the Java Women's Club # 1
I want to get the field name of the [Java] field. (Old tale tone)
[Java Spring MVC] I want to use DI in my own class
[Java] How to use the Calendar class
I translated the grammar of R and Java [Updated from time to time]
Use the l method for time notation
[Rails + Webpacker] I want to use images of assets! Until you can view the image in Vue.js
I want to play a GIF image on the Andorid app (Java, Kotlin)
You may not want to use the remove method in ArrayList very often
The training for newcomers was "Make an app!", So I made an app for the time being.
[Eclipse] I want to use the completion function, but I want to manage to confirm the completion with spaces.
I want to get only the time from Time type data ...! [Strftime] * Additional notes
[Deep Learning from scratch] in Java 1. For the time being, differentiation and partial differentiation
I tried using Docker for the first time
I want to output the day of the week
Run R from Java I want to run rJava