Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

Scala PartialFunction with isDefinedA and apply not working

I am new in Scala, i was trying PartialFunctions, is this correct way to test functionality, as some tutorials followed this to work, but not working for me?

code:

object MyScalaApp extends App {
def try29{
    val r = new PartialFunction[Int, Int]  
    { 
        def isDefinedAt(q: Int) = q < 0 // Applying isDefinedAt method  
        def apply(q: Int) = 12 * q // Applying apply method 
    }        
    val rr = new PartialFunction[Double, Double]  
    { 
        def isDefinedAt(q: Double) = {q < 0}
        def apply(q: Double) = 12 * q 
    }

    println(r(1))
    println(r(2))        
    println(rr(-1))
    println(rr(-2))
  }
  }
  try29
}

output:

12
24
-12.0
-24.0

Why apply get call when its not matching first condition?
When I write def isDefinedAt(q: Int) = q != 0 it gives println(r(0)) as output 0

question from:https://stackoverflow.com/questions/66058481/scala-partialfunction-with-isdefineda-and-apply-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the ScalaDocs page:

It is the responsibility of the caller to call isDefinedAt before calling apply...

Let's try your r() Partial Function in a context where isDefinedAt() is called automatically.

val r = new PartialFunction[Int, Int] {
  def isDefinedAt(q: Int) = q < 0
  def apply(q: Int) = 12 * q
}
List(4,-3,22,-9,0).collect(r)
//res0: List[Int] = List(-36, -108)

Seems to work as expected.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...