Search code examples
scalascala-placeholder-syntaxascription

Force grouping of ascription on underscore in scala


I am trying to do:

MyObject.myMethod(_:MyType.myAttribute)

This fails with

type myAttribute is not a member of object MyObject

which is correct. The problem is that I want to call myMethod on myAttribute of _:MyType, not ascribe MyType:myAttribute to _. Can I somehow group the type ascription _:MyType? (_:MyType).myAttribute returns type MyType => classOf(myAttribute), which is not what I want.

Edit: I changed the title and text of this post to no longer refer to this as the associativity of the dot, which I believe was not correct.


Solution

  • Are you trying to create function (m: MyType) => MyObject.myMethod(m.myAttribute) using underscore?

    If so, the problem is that MyObject.myMethod((_:MyType).myAttribute) means MyObject.myMethod((m:MyType) => m.myAttribute).

    You can use infix notation:

    MyObject myMethod (_:MyType).myAttribute
    

    Proof it works:

    scala> case class MyType(myAttribute: Int)
    defined class MyType
    
    scala> object MyObject {
         |   def myMethod(a: Int) = a.toString
         | }
    defined module MyObject
    
    scala> MyObject myMethod (_:MyType).myAttribute
    res0: MyType => java.lang.String = <function1>
    
    scala> res0(MyType(1))
    res1: java.lang.String = 1
    
    scala> MyObject myMethod (MyType(1))
    <console>:1: error: type mismatch;
     found   : MyType
     required: Int
                  MyObject myMethod (_:MyType)
                                      ^