# Scala導入ティップス

**URL:** https://forum.ficusonline.com/t/topic/385
**Category:** Programming
**Created:** [2020 年 10 月 3 日午後 2:15 UTC](https://forum.ficusonline.com/t/topic/385 "2020-10-03T14:15:15Z")
**Posts on this page:** 11
**Page:** 2

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 10 月 26 日午前 8:42 UTC](https://forum.ficusonline.com/t/topic/385/21 "2020-10-26T08:42:09Z")

</div>

### ABSTRACT CLASSES

**Trait** ではパラメータを定義できないため、パラメータを定義できる **Trait** として利用。  
**Java** コードから呼び出す際にも使用。  
拡張クラスは、 **abstract class** を一つだけしか利用できない。

> **[Abstract Classes](https://docs.scala-lang.org/overviews/scala-book/abstract-classes.html)**
>
> This page shows how to use abstract classes, including when and why you should use abstract classes.

以下 **Trait** では変数を定義できない。

```auto
trait Animal(name: String) --->コンパイルエラー

```

**abstract class** により変数を定義。

```auto
abstract class Animal(name: String)

```

**Ex) Pet(name)** が **abstract class** であることを示す。

```auto
abstract class Pet (name: String) {
    def speak: Unit = println(s"My name is $name")
}

class Dog(name: String) extends Pet(name)

val d = new Dog("Fido")
d.speak

```

クラスメンバーに **abstract type** を含む場合（具体的な値やメソッドが定義されていない）にも **abstract class** を使用。

> **[Abstract Classes in Scala - GeeksforGeeks](https://www.geeksforgeeks.org/scala/abstract-classes-in-scala/)**
>
> Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and...

```java
// Scala program to illustrate how to 
// create an abstract class 

// Abstract class 
abstract class myauthor 
{ 
	
	// abstract method 
	def details() 
} 

// GFG class extends abstract class 
class GFG extends myauthor 
{ 
	def details() 
	{ 
		println("Author name: Ankita Saini") 
		println("Topic name: Abstract class in Scala") 
	} 
} 

object Main 
{ 
	// Main method 
	def main(args: Array[String]) 
	{ 
		// objects of GFG class 
		var obj = new GFG() 
		obj.details() 
	} 
} 

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 10 月 26 日午後 3:07 UTC](https://forum.ficusonline.com/t/topic/385/22 "2020-10-26T15:07:13Z")

</div>

### ABSTRACT TYPE MEMBERS

具体的な型のタイプ、値、メソッドなどを定義していないクラスメンバー

> **[Abstract Type Members](https://docs.scala-lang.org/tour/abstract-type-members.html)**

> **[Scala | Abstract Type members - GeeksforGeeks](https://www.geeksforgeeks.org/scala/scala-abstract-type-members/)**
>
> Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and...

```java
// Scala program of abstract type member 

// Declaring an abstract class 
abstract class vehicle (name:String) 
{	 
	// This is an abstract member 
	// with undefined implementation 
	val category: String	 
	
	// A function that is used to print 
	// the value of the abstract member 
	def car_type{ println(category) } 
	override def toString = s" The vehicle type is $category"
} 

// Now extend the classes bike, car, 
// truck and bus and provide values 
// for the variable type 

class car (name:String) extends vehicle (name) 
{ 
	// assigning the value of 
	// the abstract member as car 
	val category = "car"			
} 
class bike (name:String) extends vehicle (name) 
{ 
	// assigning the value of 
	// the abstract member as bike 
	val category = "bike"		
} 
class bus (name:String) extends vehicle (name) 
{ 
	// assigning the value of 
	// the abstract member as bus 
	val category = "bus"			
} 
class truck (name:String) extends vehicle (name) 
{ 
	// assigning the value of 
	// the abstract member as truck 
	val category = "truck"		
} 

object AbstractFieldsDemo extends App 
{ 
	// assigning the name as Honda in the abstract 
	// class where the category value is car 
	val car = new car("Honda") 
	
	// assigning the name as Yamaha in the abstract 
	// class where the category value is bike 
	val bike = new bike("Yamaha") 
	
	// assigning the name as Tata in the abstract 
	// class where the category value is bus 
	val bus = new bus("Tata")	 
	
	// assigning the name as Ashok_Leyland in the 
	// abstract class where the category value is truck 
	val truck = new truck("Ashok_Leyland") 
	
	// implementing the function 
	// car_type for the object car 
	car.car_type 
	
	// implementing the function 
	// car_type for the object bus 
	bus.car_type 
	
	// implementing the function 
	// car_type for the object truck 
	truck.car_type	 
	
	// implementing the function 
	// car_type for the object bus 
	bike.car_type	 
	println(car) 
	println(bus) 
	println(truck) 
	println(bike) 
} 

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 10 月 27 日午前 9:05 UTC](https://forum.ficusonline.com/t/topic/385/23 "2020-10-27T09:05:09Z")

</div>

### Keywords/reserved symbols

> **[Redirecting…](https://docs.scala-lang.org/tutorials/FAQ/finding-symbols.html)**

```
// Keywords
<- // Used on for-comprehensions, to separate pattern from generator
=> // Used for function types, function literals and import renaming

// Reserved
( ) // Delimit expressions and parameters
[] // Delimit type parameters
{ } // Delimit blocks
. // Method call and path separator
// /* */ // Comments
# // Used in type notations
: // Type ascription or context bounds
<: >: // Upper and lower bounds
<% // View bounds (deprecated)
" """ // Strings
' // Indicate symbols and characters
@ // Annotations and variable binding on pattern matching
` // Denote constant or enable arbitrary identifiers
, // Parameter separator
; // Statement separator
_* // vararg expansion
_ // Many different meanings

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 10 月 30 日午前 7:17 UTC](https://forum.ficusonline.com/t/topic/385/24 "2020-10-30T07:17:26Z")

</div>

### MODIFIERS

Method modifiers should be given in the following order (when each is applicable):

Annotations, each on their own line

Override modifier ( **override** )  
Access modifier ( **protected, private** )  
Implicit modifier ( **implicit** )  
Final modifier ( **final** )

```auto
def
@Transaction
@throws(classOf[IOException])
override protected final def foo(): Unit = {
  ...
}

```

## Override

サブクラスによる元クラスの内容（メソッド）を上書き（変数の定義は不変）

> **[Method Overriding in Scala - GeeksforGeeks](https://www.geeksforgeeks.org/scala/method-overriding-in-scala/)**
>
> Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and...

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 10 月 30 日午後 2:35 UTC](https://forum.ficusonline.com/t/topic/385/25 "2020-10-30T14:35:38Z")

</div>

## Self Reference(this)

On the inside of a class, the name **this** represents the object on which the current method is executed.

Add the functions less and max to the class Rational.

```auto
  class Rational(x: Int, y: Int) {
    ...
    def less(that: Rational) =
    numer * that.denom < that.numer * denom

    def max(that: Rational) =
      if (this.less(that)) that else this
  }

```

Note that a simple name x, which refers to another member of the class, is an abbreviation of **this.x**. Thus, an equivalent way to formulate less is as follows.

```auto
  def less(that: Rational) =
    this.numer * that.denom < that.numer * this.denom

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 10 月 30 日午後 3:02 UTC](https://forum.ficusonline.com/t/topic/385/26 "2020-10-30T15:02:09Z")

</div>

## Predef

> **[Predef](https://www.scala-lang.org/api/current/scala/Predef$.html)**

### Assertions

These methods support program verification and runtime correctness.

```java
final def assert(assertion: Boolean, message: => Any): Unit
Tests an expression, throwing an AssertionError if false.

def assert(assertion: Boolean): Unit
Tests an expression, throwing an AssertionError if false.

final def assume(assumption: Boolean, message: => Any): Unit
Tests an expression, throwing an AssertionError if false.

def assume(assumption: Boolean): Unit
Tests an expression, throwing an AssertionError if false.

final def require(requirement: Boolean, message: => Any): Unit
Tests an expression, throwing an IllegalArgumentException if false.

def require(requirement: Boolean): Unit
Tests an expression, throwing an IllegalArgumentException if false.

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 10 月 31 日午前 9:41 UTC](https://forum.ficusonline.com/t/topic/385/27 "2020-10-31T09:41:40Z")

</div>

## def, val, var

> <https://stackoverflow.com/questions/4437373/use-of-def-val-and-var-in-scala>

**def** - defines an immutable label for the right side content which is lazily evaluated - evaluate by name.

**val** - defines an immutable label for the right side content which is eagerly/immediately evaluated - evaluated by value.

**var** - defines a mutable variable, initially set to the evaluated right side content.

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 11 月 9 日午前 6:32 UTC](https://forum.ficusonline.com/t/topic/385/28 "2020-11-09T06:32:19Z")

</div>

### LazyLists " #:: "

> **[Concrete Immutable Collection Classes](https://docs.scala-lang.org/overviews/collections-2.13/concrete-immutable-collection-classes.html)**

以下のようなフィボナッチ数列の演算で、 **#::** とすることで結果を呼び出さない限り演算しないようにする。

```auto
scala> def fibFrom(a: Int, b: Int): LazyList[Int] = a #:: fibFrom(b, a + b)
def fibFrom(a: Int, b: Int): LazyList[Int]

```

パラメータ入力しても演算結果を返さない。

```auto
scala> val fibs = fibFrom(1, 1).take(7)
val fibs: scala.collection.immutable.LazyList[Int] = LazyList(<not computed>)

```

**toList** メソッドによる呼び出し

```auto
scala> fibs.toList
val res0: List[Int] = List(1, 1, 2, 3, 5, 8, 13)

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 11 月 12 日午前 2:39 UTC](https://forum.ficusonline.com/t/topic/385/29 "2020-11-12T02:39:49Z")

</div>

### POLYMORPHIC METHODS

> **[def listOfDuplicates\[A\](x: A, length: Int): List\[A\] = { if (length \< 1) Nil... -...](https://docs.scala-lang.org/tour/polymorphic-methods.html#inner-main)**
>
> Methods in Scala can be parameterized by type as well as by value. The syntax is similar to that of generic classes. Type parameters are enclosed in square brackets, while value parameters are enclosed in parentheses.

型をパラメータとする場合 **[]** 、変数は **( )** を用います。型をパラメータと定義することでメソッドの自由度が大幅に増加します。 **println** 等による具体的な値を入力して呼び出しする際には **[]** は省略できます（Scalaコンパイラーによる自動認識）。

```auto
def listOfDuplicates[A](x: A, length: Int): List[A] = {
  if (length < 1)
    Nil
  else
    x :: listOfDuplicates(x, length - 1)
}
println(listOfDuplicates[Int](3, 4)) // List(3, 3, 3, 3)
println(listOfDuplicates("La", 8)) // List(La, La, La, La, La, La, La, La)

```

> **[Scala School - Type & polymorphism basics](http://twitter.github.io/scala_school/type-basics.html)**

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 11 月 20 日午前 2:15 UTC](https://forum.ficusonline.com/t/topic/385/30 "2020-11-20T02:15:23Z")

</div>

### コンパイラオプション

> **[Scala Compiler Options](https://docs.scala-lang.org/overviews/compiler-options/index.html#Standard_Settings)**

**scala.sbt**

```auto
scalaVersion := "2.13.3"

scalacOptions ++= Seq(
  "-encoding", "utf8", // Option and arguments on same line
  "-Xfatal-warnings", // New lines for each options
  "-deprecation",
  "-unchecked",
  "-language:implicitConversions",
  "-language:higherKinds",
  "-language:existentials",
  "-language:postfixOps"
)

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2020 年 11 月 30 日午前 5:55 UTC](https://forum.ficusonline.com/t/topic/385/31 "2020-11-30T05:55:48Z")

</div>

## ScalaTest

**ScalaTestホーム**

> **[ScalaTest](https://www.scalatest.org/)**

**バージョン別ドキュメント**

> **[ScalaTest](https://www.scalatest.org/scaladoc)**

[前のページ](https://forum.ficusonline.com/t/topic/385.md?page=1)
