티스토리 뷰

scala

[scala] - trait, object, class

signalsunnyA 2020. 3. 15. 20:43

계속 헷갈리는 개념들을 정리해본다.

 

object:

object는 정확히 하나의 *instance(instance: 해당 클래스의 구조로 컴퓨터 저장공간에서 할당된 실체를 의미한다.)만 가지고 있는 class이다. 이것은 lazily하게 참조 될 때 생성되어진다. ( 마치 lazy val 처럼)

top-level value로써, singleton이다.

 

Defining a singleton object

An object는 value이다. keyword ojbect 를 사용한다.  

object Logger

이 method info는 프로그램의 어디에서나 import 할 수 있다. 

이와 같은 utility methods 생성은 일반적인 singleton objects 사용 사례이다.

다른 pakage에서 어떻게 앞에 생성한 code info를 사용하는지를 알아보자.

 

 

 

Companion objects

object와 class는 같은 이름과 같은 source file에 정의되어 있다. 이것은 campanions라고 한다.

companions는 properties에 특별한 접근 제어를 할 수 있다.

 

 

example:  

class와 object Retangle 선언

이 class는 companion인 createValidRectangle에 접근가능하다.

이 예제에서는 잘못된 입력(음수 값이 입력되는 것)을 처리해주는 부분을 object로 구현하고있다. 

line 6번에서 b=-10000값을 line 4번의 math.max함수를 사용해서 최소값이 1이 되도록 구현하였다.

 

trait: encapsulates method & field definitions.

class들에게 mixing되어 재사용 가능하다.

 

- 상속(inheritance)와 다른점? 

상속은 하나의 superclass로 부터 상속되여야 한다.

trait은 여러가지 trait를 class에 섞어(mix)해서 사용 할 수 있다. 

 

 

 출처: https://en.wikibooks.org/wiki/Scala/Objects

https://docs.scala-lang.org/tour/singleton-objects.html

 

Scala/Objects - Wikibooks, open books for an open world

In Scala, an object is a named instance with members such as fields and methods. An object and a class that have the same name and which are defined in the same source file are known as companions. Companions has special access control properties, which is

en.wikibooks.org

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함