Scala val syntax: what does val myVal: {def ...} mean?

I am new to Scala and funcprog.

I have a piece of code (some of you may recognize it):

    trait SwingApi {

      type ValueChanged <: Event

      val ValueChanged: {
        def unapply(x: Event): Option[TextField]
      }
      ...
     }

where I have not underestimated and what val ValueChanged: {...} is.

From this post, I learned that

type ValueChanged <: Event

and

val ValueChanged: {
            def unapply(x: Event): Option[TextField]
          }

are two unrelated things because they are in different namespaces, etc., and the ValueChanged type is an abstract subtype of the event.

Ok, then I try on a Scala sheet:

type myString <: String

 val myString: {
    def myfunc(x: String): String
  }

and he shows me the error "only classes can declare and undefined members" ... Isn't this a similar construct?

Finally, the questions:

  • What is ValueChanged in the val ValueChanged piece of code?

  • is it really not related to the type ValueChanged <: Event

  • what this syntax means:

    val myVal: {def func {x: T}: T}

? What is the name of the value, its type and its actual value here?

Thank!

+4
1
{def unapply(x: Event): Option[TextField]}

, , , unapply [TextField] . Duck typing, :

def foo(canQuack: {def quack(): Unit}) = {
  canQuack.quack()
}
object Bar{
   def quack(): Unit = print("quack")
}
object Baz{
   def bark(): Unit = print("bark")
}
foo(Bar) //works
foo(Baz) //compile error

type StructuralType = {def unapply(x: Event): Option[TextField]}
val ValueChanged: StructuralType

val ValueChanged Type StructuralType, , , .

,

trait SwingApi {
...
  val ValueChanged: {
    def unapply(x: Event): Option[TextField]
  }
...
}

, SwingApi /, val ValueChanged , , unapply

trait SwingApi {
  val ValueChanged: {
    def unapply(x: Event): Option[TextField]
  }
}
//works:
object Bar extends SwingApi{
  val ValueChanged = {
    def unapply(x: Event): Option[TextField] = None
  }
}
//compile error:
object Baz extends SwingApi{
  val ValueChanged = {
    //wrong name
    def foo(x: Event): Option[TextField] = None
  }
}
//compile error:
object Baz2 extends SwingApi{
  val ValueChanged = {
    //wrong input/output type
    def unapply(): Unit = {}
  }
}

+7

All Articles