How to write Scala from the perspective of Java

As the title says. I wanted to do Scala, so I summarized it. Scheduled to be updated each time during learning. By the way, my background is C # 4 years and Java 1 year.

Naming convention

It looks good as Java. Camel case

Detailed rules

--No need for a trailing semicolon --Comments are the same // and / * * /

variable

Type inference works with declarations! (From 10 for Java)

val hoge = 1 //immutable (variable with final)
var hoge = 1 //mutable (variable)

With type specification,

val i:Int = 1
val str:String = "Hi!"

To embed a variable in a string, prefix the literal with s and prefix the variable with $.

val firstName = j
val familyName = ichikawa
val str = s"my name is $firstName - $familyName"

You can also embed code inside literals

val str = s"My weight is ${weight + 3}"

if statement

Writing is the same Can be written as an expression that returns a value

val age = 30
val result =
  if (age >= 30) "over 30"
    else "under 30"
println(result)// over 30

operator

It's basically the same, but it seems that there is no ternary operator. Since the value can be returned with if, it can be substituted

val result = if (age >= 30) "over 30" else "under 30"

switch It seems to say match

val team = "So"
val result = team match {
  case "B" | "seagull" => "Bッテ" //or condition
  case other => s"undefined: ${other}" // default
}
println(result)
// undefined:So

loop

while is the same, but different from for It seems that the condition is called a generator

for (i <- 0 to 3) println(i) //The condition can be 0 until 4 and can be 0 or more and less than 4.
// 0
// 1
// 2
// 3

for (i <- 0 to 3 if i != 2) println(i) //Conditional
// 0
// 1
// 3

var result = for (i <- 0 to 3) yield i //Get results
for (i <- result) println(i)

for (i <- 0 to 3; j <- 0 to 3) println(s"$i, $j") //for nesting

Method

With java

public void sayHello() {
  System.out.println("hello");
}
    
public String sayHelloStr() {
  return "hello";
}
    
public String getHelloMessage(String firstName, String familyName) {
  return "Hello " + firstName + " " + familyName;
}

But,

def sayHello: Unit = {
  println("hello")
}
    
def getHelloStr: String = {
  "Hello" //return Optional
}
    
def getHelloMessage(firstName: String, familyName: String): String = {
  s"Hello $firstName $familyName"
  // firstName: String = "taro"You can set the default value like this. C#Is the same as
}

class

class Human(val name: String) { //Become a constructor with parameter definition
  def sayHello() = println("hello") //Lambda-like method definition
}

//Instantiation
val human = new Human("j-ichikawa")
val name = human.name;
human.sayHello()

Inheritance is

class PerfectHuman(name: String) extends Human(name) {
  override def sayHello() = println("perfect hello")
}

package

Declaration is the same

package aaa.bbb.ccc

The call is

import aaa.bbb.ccc.ddd //Individual
import aaa.bbb.ccc.ddd.{ddd, eee} //Multiple
import aaa.bbb.ccc.ddd._ //collect

Access modifier

public, protected, private The way to attach and see to the members of the attached class is the same If nothing is attached, it will be public by default (private is the default in C #, isn't it? final The function when attached to a class or member is the same as Java. Declare with val to make the variable immutable

object It seems to be a keyword, not a type Add object to the class with the same name

//It's like a companion object
object Human {
  def sayHello() = println("hello") //Can be called without instantiation like a class method
  def apply(name: String) = new Human(name) //Become a factory method definition
}

//This is a companion class
class Human (val name: String) {
  def sayHello() = println("hello")
}

//How to use companion objects
Human.sayHello()
val taro = Human("taro") //Generate taro instance

println seems to be a method of an object called Predef

A new concept. ..

Abstract class

Yeah, no resistance

abstract class Animal {
  def cry()
}

class Cat extends Animal {
  def cry() = println("Nyaaaa")
}

Interface

It seems to be a trait

trait Runnable {
  def run() = println("Dadada. .. ..")
}

class Player extends Runnable //Same syntax as implementation inheritance C#Same as
class SuperPlayer extends Player with Runnable //If inherited, implement with with

Updating. .. ..

Recommended Posts

How to write Scala from the perspective of Java
[Java] Memo on how to write the source
[Java] How to get the authority of the folder
How to write java comments
[Java] How to get the URL of the transition source
[Java] Types of comments and how to write them
[Java] How to extract the file name from the path
Java language from the perspective of Kotlin and C #
[Java] How to get the maximum value of HashMap
Studying Java # 6 (How to write blocks)
How to write Java variable declaration
The road from JavaScript to Java
Get to the abbreviations from 5 examples of iterating Java lists
Comparison of how to write Callback function (Java, JavaScript, Ruby)
How to get the longest information from Twitter as of 12/12/2016
How to write and notes when migrating from VB to JAVA
How to derive the last day of the month in Java
[Java] How to use the File class
[Java] How to use the hasNext function
[java] Summary of how to handle char
[Java] How to use the HashMap class
Summary of how to write annotation arguments
[Introduction to Java] How to write a Java program
Basics of Java development ~ How to write programs (variables and types) ~
[Java] How to use the toString () method
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
[Java] How to output and write files!
How to determine the number of parallels
[Java] How to set the Date time to 00:00:00
[Java] How to get the current directory
Ruby from the perspective of other languages
[Java] [Maven3] Summary of how to use Maven3
[Processing × Java] How to use the class
Java: How to send values from Servlet to Servlet
How to sort the List of SelectItem
How to install the legacy version [Java]
How to get the date in java
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
Output of the book "Introduction to Java"
[Processing × Java] How to use the function
[Java] How to use the Calendar class
[Java] How to convert from String to Path type and get the path
How to check for the contents of a java fixed-length string
How to write offline real-time Java implementation example of F01 problem
Introduction to Scala from a Java perspective, decompiled and understood (basic)
How to get the length of an audio file in java
How to increment the value of Map in one line in Java
Let's summarize the Java 8 grammar from the perspective of an iOS engineer
[Java] How to retrieve the parameters passed from html on the server side
Introduction to Scala from a Java perspective (Class-Tuple edition) to decompile and understand
How to find out the Java version of a compiled class file
[Java] How to get to the front of a specific string using the String class
How to find the total number of pages when paging in Java
How to get the absolute path of a directory running in Java
[Java improvement case] How to reach the limit of self-study and beyond
From Java9, the constructor of the class corresponding to primitive types is deprecated.
I translated the grammar of R and Java [Updated from time to time]
JDBC promises and examples of how to write
How to find the cause of the Ruby error
[java] Summary of how to handle character strings