简体   繁体   中英

Unable to declare functor type that takes zero parameters?

I'm trying to make a type definition for the function type () => Unit, I use this signature quite a bit for cleanup callback functions, and I'd like to give them more meaningful names.

I've tried the following, which I think should be correct syntax, but it doesn't compile:

package myPackage

import stuff

type CleanupCallback = () => Unit

trait myTrait ...

class mObject ...

Why doesn't it compile? And what is the correct syntax?

The compilation error is: expected class or object definition

You can't declare type alias out of class/trait/object scope. But you can declare it in package object as follows:

package object myPackage {
  type CleanupCallback = () => Unit
}

It will be visible for all classes in myPackage .

Also you can import it in other classes which belong to other packages:

import myPackage.CleanupCallback 

trait MyTrait {
  def foo: CleanupCallBack
}

IDEA plugin supports creation of package objects, another version is (suppose you don't have IDEA plugin):

Create file package.scala in your package. The file must contain:

package object packageName { // name must match with package name
  // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM