This question already has answers here:
What does the `#` operator mean in Scala?
(4 answers)
Closed 5 years ago.
I found the following syntax in Scala. I have never seen # and couldn't find much information about it? What does # mean?
case class WithRole(role: Role) extends Authorization[User, DefaultEnv#A]
It's one of way in scala to refer a type. I quote from Scala in Depth:
Types within Scala are referred to via two mechanisms: the hash ( #) and dot ( .)
operators. The dot operator can be thought of doing the same for types as it does for
members of an object. It refers to a type found on a specific object instance. This is
known as a path-dependent type. When a method is defined using the dot operator
to a particular type, that type is bound to a specific instance of the object. This means
that you can’t use a type from a different object, of the same class, to satisfy any type
constraints made using the dot operator. The best way to think of this is that there’s a
path of specific object instances connected by the dot operator. For a variable to
match your type, it must follow the same object instance path. You can see an exam-
ple of this later.
The hash operator ( # ) is a looser restriction than the dot operator. It’s known as a
type projection, which is a means of referring to a nested type without requiring a
path of object instances. This means that you can reference a nested type as if it
weren’t nested.
Related
As the title suggests I am trying to reference a Nested Generic Type in Powershell Core.
I found that the + sign is used instead of the . for accessing a nested type in Powershell... but the syntax doesn't seem to work for "Nested Generic Types"... the compiler doesn't like the code an errors about the syntax.
Special use of plus (+) sign in Powershell
Has anyone been successful in getting this to work or is it a known limitation?
[System.Collections.Generic.Dictionary[[string], [int]]+Enumerator] GetEnumerator()
Daniel has provided the solution:
[System.Collections.Generic.Dictionary`2+Enumerator[string, int]]
returns the type of interest (note that the nested [...] around the individual generic type arguments, string and int, are optional).
That is, before being able to specify type arguments in order to construct a generic type, you must first specify its open form, which requires specifying the generic arity (the count of type arguments, <n>) in the form `<n> following the type name, namely `2 in the case of System.Collections.Generic.Dictionary<TKey,TValue> (expressed in C# notation), using the language-agnostic .NET API notation, as explained in this answer.
If no nested type (suffixed with +<typename>) is involved, specifying the arity is optional if all type arguments are specified; e.g., instead of [System.Collections.Generic.Dictionary`2[string, int]], [System.Collections.Generic.Dictionary[string, int]] is sufficient.
However, the enumerator type in question has no public constructor, so you cannot instantiate it directly; rather, it is the type returned when you call .GetEnumerator() on (a constructed form of) the enclosing type, [System.Collections.Generic.Dictionary`2]; verify with:
Get-Member -InputObject ([System.Collections.Generic.Dictionary[string, int]])::new().GetEnumerator()
Why is it that, in Powershell, the System.DayOfWeek enum can be referred to like [System.DayOfWeek], whereas the System.Environment.SpecialFolder enum must be referred to like [System.Environment+SpecialFolder] (note the plus character)?
My guess is because SpecialFolder is part of the static Environment class and DayOfWeek is sitting directly in the System namespace, but I'm having trouble finding any information on this. Normally static members would use the "static member operator", but that doesn't work in this case, nor does anything else I try except the mysterious plus character...
[System.DayOfWeek] # returns enum type
[enum]::GetValues([System.DayOfWeek]) # returns enum values
[enum]::GetValues([System.Environment.SpecialFolder]) # exception: unable to find type
[enum]::GetValues([System.Environment]::SpecialFolder) # exception: value cannot be null
[enum]::GetValues([System.Environment+SpecialFolder]) # returns enum values
System.Environment.SpecialFolder is definitely a type, and in C# both enums work the same way:
Enum.GetValues(typeof(System.Environment.SpecialFolder)) // works fine
Enum.GetValues(typeof(System.DayOfWeek)) // also works
I'd really like to understand why there's a distinction in Powershell and the reasoning behind this behaviour. Does anyone know why this is the case?
System.Environment.SpecialFolder is definitely a type
Type SpecialFolder, which is nested inside type Environment, is located in namespace System:
C# references that type as a full type name as in the quoted passage; that is, it uses . not only to separate the namespace from the containing type's name, but also to separate the latter from its nested type's name.
By contrast, PowerShell uses a .NET reflection method, Type.GetType(), to obtain a reference to the type at runtime:
That method uses a language-agnostic notation to identify types, as specified in documentation topic Specifying fully qualified type names.Tip of the hat to PetSerAl.
In that notation, it is + that is used to separate a nested type from its containing type (not ., as in C#).
That is, a PowerShell type literal ([...]) such as:
[System.Environment+SpecialFolder]
is effectively the same as taking the content between [ and ], System.Environment+SpecialFolder, and passing it as a string argument to Type.GetType, namely (expressed in PowerShell syntax):
[Type]::GetType('System.Environment+SpecialFolder')
Note that PowerShell offers convenient extensions (simplifications) to .NET's language-agnostic type notation, notably the ability to use PowerShell's type accelerators (such as [regex] for [System.Text.RegularExpressions.Regex]), the ability to omit the System. prefix from namespaces (e.g. [Collections.Generic.List`1[string]] instead of [System.Collections.Generic.List`1[string]]), and not having to specify the generic arity (e.g. `1) when a list of type argument is passed (e.g. [Collections.Generic.List[string]] instead of [Collections.Generic.List`1[string]] - see this answer) for more information.
I'm beginning to teach myself swift and I'm going through examples of games at the moment. I've run across a line of code that I thought was peculiar
scene.scaleMode = .ResizeFill
In languages I'm used to (C / Java) the "." notation is used to reference some sort of structure/ object but I'm not exactly sure what this line of code does as there is no specified object explicitly before the "."
Information regarding clarification of this non-specified "." reference, or when/ how it can be used, would be great
P.S. I'm using sprite kit in Xcode
In Swift, as in the other languages you mentioned, '.' is a member access operator. The syntax you are referring to is a piece of shorthand that Swift allows because it is a type-safe language.
The compiler recognises that the property you are assigning to is of type SKSceneScaleMode and so the value you are assigning must be one of that type's enumerated values - so the enumeration name can be omitted.
To add to PaulW11's answer, what's happening here is only valid syntax for enums, and won't work with any other type (class, struct, method, function). Swift knows the type of the property that you are assigning to is an enum of type SKSceneScaleMode, so lets you refer to the enum member without having to explicitly give the type of the enum (ie SKSceneScaleMode.ResizeFill).
There are some situations where there will be ambiguity, and you will have to give the full name, this will be dependant on the context. For example, you may have two different enum types in scope, that both have a matching member name.
EDIT
Updating this answers as I incorrectly specified this was only applicable to enums, which is not true. There is a good blog post here which explains in more detail
http://ericasadun.com/2015/04/21/swift-occams-code-razor/
This question already has answers here:
Dot (".") operator and arrow ("->") operator use in C vs. Objective-C
(5 answers)
Closed 9 years ago.
While reading some tutorials i found for the first time the "structure operator", I read that it's used to refer of an instace variable.
-(void)setNumber:(int)n{
self.number = n;
}
-(void)setNumber:(int)n{
self->number = n;
}
My doubt is: what it doing exactely? When do i use it? Why should i prefer it to the dot notation?
Dot syntax in Objective-C is just syntactic sugar which is replaced by the compiler with a method invocation. -> dereferences the pointer and accesses the member directly, with no method invocation.
In an Objective-C method call, you don't need to say self->foo, if your class has an instance variable named foo the compiler will infer the self-> portion of it. Because of this, while it's not completely unheard of, uses of -> with an Objective-C object are comparatively rare.
The arrow -> operator accesses instance variables directly, which you don't want in general, since it violates encapsulation and circumvents accessor methods (that can be a potential source of problems, like KVO not working or some desired side effects not taking place).
Instead, you should almost always use ., because it accesses the properties using getters and setters.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What are some example use cases for symbol literals in Scala?
What's the purpose of Symbol and why does it deserve some special literal syntax e. g. 'FooSymbol?
Symbols are used where you have a closed set of identifiers that you want to be able to compare quickly. When you have two String instances they are not guaranteed to be interned[1], so to compare them you must often check their contents by comparing lengths and even checking character-by-character whether they are the same. With Symbol instances, comparisons are a simple eq check (i.e. == in Java), so they are constant time (i.e. O(1)) to look up.
This sort of structure tends to be used more in dynamic languages (notably Ruby and Lisp code tends to make a lot of use of symbols) since in statically-typed languages one usually wants to restrict the set of items by type.
Having said that, if you have a key/value store where there are a restricted set of keys, where it is going to be unwieldy to use a static typed object, a Map[Symbol, Data]-style structure might well be good for you.
A note about String interning on Java (and hence Scala): Java Strings are interned in some cases anyway; in particular string literals are automatically interned, and you can call the intern() method on a String instance to return an interned copy. Not all Strings are interned, though, which means that the runtime still has to do the full check unless they are the same instance; interning makes comparing two equal interned strings faster, but does not improve the runtime of comparing different strings. Symbols benefit from being guaranteed to be interned, so in this case a single reference equality check is both sufficient to prove equality or inequality.
[1] Interning is a process whereby when you create an object, you check whether an equal one already exists, and use that one if it does. It means that if you have two objects which are equal, they are precisely the same object (i.e. they are reference equal). The downsides to this are that it can be costly to look up which object you need to be using, and allowing objects to be garbage collected can require complex implementation.
Symbols are interned.
The purpose is that Symbol are more efficient than Strings and Symbols with the same name are refered to the same Symbol object instance.
Have a look at this read about Ruby symbols: http://glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols
You can only get the name of a Symbol:
scala> val aSymbol = 'thisIsASymbol
aSymbol: Symbol = 'thisIsASymbol
scala> assert("thisIsASymbol" == aSymbol.name)
It's not very useful in Scala and thus not widely used. In general, you can use a symbol where you'd like to designate an identifier.
For example, the reflection invocation feature which was planned for 2.8.0 used the syntax obj o 'method(arg1, arg2) where 'o' was a method added to Any and Symbol was added the method apply(Any*) (both with 'pimp my library').
Another example could be if you want to create an easier way to create HTML documents, then instead of using "div" to designate an element you'd write 'div. Then one can imagine adding operators to Symbol to make syntactic sugar for creating elements