What are the benefits of having a feature behind an object?

In the Scala 2.11 standard library, we see:

object StdIn extends StdIn

What benefits does it bring? There is no other class that extends this trait. Does this convey a sign in function calls? What is the need when there is a singleton object?

+4
source share
2 answers

First of all, the presence of an object that extends the trait does not limit us to the creation of additional instances of this trait. In a hypothetical situation, there may be a different version / implementation that is superior StdIn, and we could declare the previous object obsolete while maintaining the same interface. However, this is not the intention in the case StdInaccording to scaladoc :

/** private[scala] because this is not functionality we should be providing
 *  in the standard library, at least not in this idiosyncractic form.
 *  Factored into trait because it is better code structure regardless.
 */
private[scala] trait StdIn {

. . , , :

scala> object A { val id = 1 }
defined object A

scala> def f(v: A.type) = v.id
f: (v: A.type)Int

scala> f(A)
res1: Int = 1

scala> def f(v: A) = v.id
<console>:10: error: not found: type A
       def f(v: A) = v.id

:

scala> def g(v: { def id: Int }) = v.id
g: (v: AnyRef{def id: Int})Int

scala> object B { val id = 2 }
defined object B

scala> g(B)
res5: Int = 2

scala> g(A)
res6: Int = 1

scala> f(B)
<console>:17: error: type mismatch;
 found   : B.type
 required: A.type
       f(B)
         ^

StdIn, :

scala> import scala.io._
import scala.io._

scala> val b: StdIn = ???
<console>:13: error: trait StdIn in package io cannot be accessed in package io
       val b: StdIn = ???
              ^

, , , , - : /.

+2

.

, - , .

trait Friendly {
  def greet() { println("hi there") }
}

object Friendly extends Friendly

. . , , Friendly. , Friendly mix , ( Friendly ):

object MixinExample extends Application with Friendly {
  greet()
}

Friendly , :

import Friendly._

object ImportExample extends Application {
  greet()
}
+5

Source: https://habr.com/ru/post/1624382/


All Articles